using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; namespace rySafe { /// /// AES加密解密类 /// public class AES { //默认密钥向量 private static readonly byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// /// AES加密算法 /// /// 明文字符串 /// 密钥 /// 返回加密后的密文字节数组 public static byte[] AESEncrypt(string plainText, string strKey) { //分组加密算法 SymmetricAlgorithm des = Rijndael.Create(); byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 //设置密钥及密钥向量 des.Key = Encoding.UTF8.GetBytes(strKey); des.IV = _key1; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组 cs.Close(); ms.Close(); return cipherBytes; } /// /// AES解密 /// /// 密文字节数组 /// 密钥 /// 返回解密后的字符串 public static byte[] AESDecrypt(byte[] cipherText, string strKey) { SymmetricAlgorithm des = Rijndael.Create(); des.Key = Encoding.UTF8.GetBytes(strKey); des.IV = _key1; byte[] decryptBytes = new byte[cipherText.Length]; MemoryStream ms = new MemoryStream(cipherText); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read); cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); return decryptBytes; } /// /// 加密 /// /// /// /// public static string Encode(string data,string pass) { byte[] encryptBytes = AESEncrypt(data, ConvertKey(pass)); return Convert.ToBase64String(encryptBytes); //将加密后的密文转换为Base64编码,以便显示,可以查看下结果 } /// /// 解码 /// /// /// /// public static string Decode(string data, string pass) { try { //解密 byte[] decryptBytes = AESDecrypt(Convert.FromBase64String(data), ConvertKey(pass)); //将解密后的结果转换为字符串,也可以将该步骤封装在解密算法中 string result = Encoding.UTF8.GetString(decryptBytes); return result.Replace("\0", ""); } catch { return ""; } } /// /// 转换密钥到合法密钥 /// /// /// public static string ConvertKey(string pass) { string sxStr = MD5Sha1.GetMD5(pass); if (sxStr.Length > 32) { return sxStr.Substring(0, 32); } else { return (sxStr + sxStr).Substring(0, 32); } } } }