使用AES加密的帮助类
在开发中经常使用加密/解密对一些内容进行处理,比如密码在存入数据库之前先经过加密处理等等,这里就把一个加密帮助类代码贴出来,供以后查找使用。
这个帮助类主要功能是对字符串和字节数组进行加密解密处理。
public class EncryptionHelper { //默认密钥向量 private static readonly byte[] DefaultKey = {0x12, 0x34, 0x56, 120, 0x90, 0xab, 0xcd, 0xef}; /// <summary> /// 解密字节数组 /// </summary> /// <param name="cipherBytes">密文字节数组</param> /// <param name="password">密钥</param> /// <returns>解密后字节数组</returns> public static byte[] DecryptBytes(byte[] cipherBytes, string password) { byte[] buffer; try { using (Aes aes = new AesManaged()) { //设置密钥及密钥向量 aes.Key = new Rfc2898DeriveBytes(password, DefaultKey).GetBytes(0x10); aes.IV = aes.Key; using (var memoryStream = new MemoryStream()) { using ( var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(cipherBytes, 0, cipherBytes.Length); cryptoStream.Flush(); } //得到解密后的字节数组 buffer = memoryStream.ToArray(); } } } catch { buffer = null; } return buffer; } /// <summary> /// 解密字符串 /// </summary> /// <param name="cipherText">密文</param> /// <param name="password">密钥</param> /// <returns>解密后字符串</returns> public static string DecryptString(string cipherText, string password) { byte[] decryptBytes = DecryptBytes(Convert.FromBase64String(cipherText), password); if (decryptBytes == null) { return null; } return Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); } /// <summary> /// 加密字节数组 /// </summary> /// <param name="plainBytes">明文字节数组</param> /// <param name="password">密钥</param> /// <returns>加密后字节数组</returns> public static byte[] EncryptBytes(byte[] plainBytes, string password) { byte[] buffer; try { using (Aes aes = new AesManaged()) { //设置密钥及密钥向量 aes.Key = new Rfc2898DeriveBytes(password, DefaultKey).GetBytes(0x10); aes.IV = aes.Key; using (var memoryStream = new MemoryStream()) { using ( var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(plainBytes, 0, plainBytes.Length); cryptoStream.FlushFinalBlock(); } //得到加密后的字节数组 buffer = memoryStream.ToArray(); } } } catch { buffer = null; } return buffer; } /// <summary> /// 加密字符串 /// </summary> /// <param name="plainText">明文</param> /// <param name="password">密钥</param> /// <returns>加密后字符串</returns> public static string EncryptString(string plainText, string password) { byte[] cipherBytes = EncryptBytes(Encoding.UTF8.GetBytes(plainText), password); if (cipherBytes == null) { return null; } return Convert.ToBase64String(cipherBytes); } }