forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSM4Helper.cs
More file actions
96 lines (81 loc) · 2.89 KB
/
SM4Helper.cs
File metadata and controls
96 lines (81 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace Blog.Core.Common.Helper.SM
{
public class SM4Helper
{
public String secretKey = "1234567890123456";// 16位
public String iv = "";
public bool hexString = false;
private SByte[] Byte2SByte(byte[] myByte)
{
sbyte[] mySByte = new sbyte[myByte.Length];
for (int i = 0; i < myByte.Length; i++)
{
if (myByte[i] > 127)
mySByte[i] = (sbyte)(myByte[i] - 256);
else
mySByte[i] = (sbyte)myByte[i];
}
return mySByte;
}
private byte[] SByte2Byte(sbyte[] orig)
{
byte[] arr = new byte[orig.Length];
Buffer.BlockCopy(orig, 0, arr, 0, orig.Length);
return arr;
}
public String Encrypt_ECB(String plainText)
{
SM4_Context ctx = new SM4_Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_ENCRYPT;
SByte[] keyBytes;
if (hexString)
{
keyBytes = null;// Hex.Decode(secretKey);
}
else
{
keyBytes = Byte2SByte(Encoding.UTF8.GetBytes(secretKey));
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_enc(ctx, keyBytes);
SByte[] bytes = Byte2SByte(Encoding.UTF8.GetBytes(plainText));
SByte[] encrypted = sm4.sm4_crypt_ecb(ctx, bytes);
//String cipherText = Encoding.UTF8.GetString(Hex.Encode(SByte2Byte(encrypted)));
String cipherText = new Base64Encoder().GetEncoded(SByte2Byte(encrypted));
if ((cipherText != null) && (cipherText.Trim().Length > 0))
{
var matchCol = Regex.Matches(cipherText, "\\s*|\t|\r|\n", RegexOptions.Multiline);
for (int i = matchCol.Count - 1; i >= 0; i--)
{
Match item = matchCol[i];
cipherText.Remove(item.Index, item.Length);
}
}
return cipherText;
}
public String Decrypt_ECB(String cipherText)
{
SM4_Context ctx = new SM4_Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_DECRYPT;
SByte[] keyBytes;
if (hexString)
{
keyBytes = null;// Hex.Decode(secretKey);
}
else
{
keyBytes = Byte2SByte(Encoding.UTF8.GetBytes(secretKey));
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_dec(ctx, keyBytes);
SByte[] decrypted = sm4.sm4_crypt_ecb(ctx, Byte2SByte(new Base64Decoder().GetDecoded(cipherText)));
return Encoding.UTF8.GetString(SByte2Byte(decrypted));
}
}
}