AES加密(128位):
1 /// <summary> 2 /// 有密碼的AES加密 3 /// </summary> 4 internal static string Encrypt(string toEncrypt) 5 { 6 var keyArray = Encoding.GetEncoding(Charset).GetBytes(key);; 7 var toEncryptArray = Encoding.GetEncoding(Charset).GetBytes(toEncrypt); 8 using (var acsp = new AesCryptoServiceProvider { KeySize = 128, BlockSize = 128 }) 9 { 10 acsp.GenerateIV(); 11 using (var aes = new AesCryptoServiceProvider { Key = keyArray, IV = acsp.IV, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }) 12 { 13 byte[] resultArray; 14 using (var cTransform = aes.CreateEncryptor()) 15 { 16 resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 17 } 18 return Convert.ToBase64String(resultArray); 19 } 20 } 21 }
AES解密(128位):
1 /// <summary> 2 /// AES解密 3 /// </summary> 4 internal static string Decrypt(string toDecrypt, string key) 5 { 6 var keyArray = Encoding.GetEncoding(Charset).GetBytes(key); 7 var toDecryptArray = Convert.FromBase64String(toDecrypt); 8 using (var acsp = new AesCryptoServiceProvider { KeySize = 128, BlockSize = 128 }) 9 { 10 acsp.GenerateIV(); 11 using (var aes = new AesCryptoServiceProvider { Key = keyArray, IV = acsp.IV, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }) 12 { 13 byte[] resultArray; 14 using (var cTransform = aes.CreateDecryptor()) 15 { 16 resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); 17 } 18 return Encoding.GetEncoding(Charset).GetString(resultArray); 19 } 20 } 21 }