-
Notifications
You must be signed in to change notification settings - Fork 62
/
AlipayEncrypt.cs
100 lines (82 loc) · 3.03 KB
/
AlipayEncrypt.cs
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
97
98
99
100
using System;
using System.Text;
using System.Security.Cryptography;
namespace Aop.Api.Util
{
public class AlipayEncrypt
{
/// <summary>
/// 128位0向量
/// </summary>
private static byte[] AES_IV = initIv(16);
/// <summary>
/// AES 加密
/// </summary>
/// <param name="encryptKey"></param>
/// <param name="bizContent"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string AesEncrypt(string encryptKey, string bizContent, string charset)
{
Byte[] keyArray = Convert.FromBase64String(encryptKey);
byte[] toEncryptArray;
if (string.IsNullOrEmpty(charset))
{
toEncryptArray = Encoding.UTF8.GetBytes(bizContent);
}
else
{
toEncryptArray = Encoding.GetEncoding(charset).GetBytes(bizContent);
}
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
rDel.IV = AES_IV;
ICryptoTransform cTransform = rDel.CreateEncryptor(rDel.Key, rDel.IV);
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray);
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="encryptKey"></param>
/// <param name="bizContent"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string AesDencrypt(string encryptKey, string bizContent, string charset)
{
Byte[] keyArray = Convert.FromBase64String(encryptKey);
Byte[] toEncryptArray = Convert.FromBase64String(bizContent);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
rDel.IV = AES_IV;
ICryptoTransform cTransform = rDel.CreateDecryptor(rDel.Key, rDel.IV);
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
if (string.IsNullOrEmpty(charset))
{
return Encoding.UTF8.GetString(resultArray);
}
else
{
return Encoding.GetEncoding(charset).GetString(resultArray);
}
}
/// <summary>
/// 初始化向量
/// </summary>
/// <param name="blockSize"></param>
/// <returns></returns>
private static byte[] initIv(int blockSize)
{
byte[] iv = new byte[blockSize];
for (int i = 0; i < blockSize; i++)
{
iv[i] = (byte)0x0;
}
return iv;
}
}
}