C# AES加密类

本文最后更新于$day天前,文中所描述的信息可能已发生改变。

1、序言

各种语言对加密类使用都有极其不太一样的方法,无论是Nodejs、Python、还是C#,加密是要注意原格式编码、Key编码、VI编码。还要注意加密填充方法(Padding),非128位Key填充方法。最优解当然是都是使用byte[]进行操作,这样可以在各种语言上做到一个统一。好像自MD5以后,我还没发现有什么语言可以直接一个 MD5(参数),能直接生成Hash或者密文。

2、类的作用

这个类可以用不长于32位为UTF-8字符进行AES加密,会自动用空格填充不足32位字符。加密方法使用ECB,这个是一个不需要向量的方法。密文填充方式用PKCS7。可以使用文字加密、JSON文本加密,或者加密Byte[]。

3、源代码

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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
public static class AES
{
public const string AesKey = "AES";
/// <summary>
/// 文字解密返回UTF8字符
/// </summary>
/// <param name="Data"></param>
/// <param name="Key"></param>
/// <returns></returns>
public static string AESDecrypt(String Data, String Key = AesKey)
{
return Encoding.UTF8.GetString(AESDecrypt(Convert.FromBase64String(Data), Key));

}
/// <summary>
/// 文字加密,返回Base64编码
/// </summary>
/// <param name="Data"></param>
/// <param name="Key"></param>
/// <returns></returns>
public static string AESEncrypt(String Data, String Key = AesKey)
{
return Convert.ToBase64String(AESEncrypt(Encoding.UTF8.GetBytes(Data), Key));
}

public static byte[] AESEncrypt(byte[] Data, String Key = AesKey)
{
MemoryStream mStream = new MemoryStream();
RijndaelManaged aes = new RijndaelManaged();

byte[] plainBytes = Data;
Byte[] bKey = new Byte[32];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 128;
aes.Key = bKey;
CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
try
{
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
return mStream.ToArray();
}
finally
{
cryptoStream.Close();
mStream.Close();
aes.Clear();
}

}

public static byte[] AESDecrypt(byte[] Data, String Key = AesKey)
{
Byte[] encryptedBytes = Data;
Byte[] bKey = new Byte[32];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
MemoryStream mStream = new MemoryStream(encryptedBytes);
RijndaelManaged aes = new RijndaelManaged();
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 128;
aes.Key = bKey;
CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
try
{
byte[] tmp = new byte[encryptedBytes.Length + 32];
int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
byte[] ret = new byte[len];
Array.Copy(tmp, 0, ret, 0, len);
return ret;
}
finally
{
cryptoStream.Close();
mStream.Close();
aes.Clear();
}
}
}
}