AES加密解密 助手类 CBC加密模式
string str = "2018"; string result1 = AESHelper.AesEncrypt(str); string result2 = AESHelper.AesDecrypt(result1);
namespace Demo { /// <summary> /// AES加密解密 助手类 /// CBC加密模式 /// </summary> public class AESHelper { /// <summary> /// 默认密钥-长度32位 /// </summary> private const string Key = "32位"; /// <summary> /// 默认向量-长度16位 /// </summary> private const string Iv = "16位"; /// <summary> /// AES加密 /// </summary> /// <param name="str">需要加密字符串</param> /// <returns>加密后字符串</returns> public static string AesEncrypt(string str) { return Encrypt(str, Key); } /// <summary> /// AES解密 /// </summary> /// <param name="str">需要解密字符串</param> /// <returns>解密后字符串</returns> public static string AesDecrypt(string str) { return Decrypt(str, Key); } /// <summary> /// AES 加密 /// </summary> /// <param name="str">明文(待加密)</param> /// <param name="key">密文</param> /// <returns></returns> private static string Encrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); RijndaelManaged rm = new RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, IV = Encoding.UTF8.GetBytes(Iv) }; ICryptoTransform cTransform = rm.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// AES 解密 /// </summary> /// <param name="str">明文(待解密)</param> /// <param name="key">密文</param> /// <returns></returns> private static string Decrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Convert.FromBase64String(str); RijndaelManaged rm = new RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, IV = Encoding.UTF8.GetBytes(Iv) }; ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } } }
文章内容参考于(原出处):
C#几种常用的加密方式
C#加密解密(AES)-AESHelper
作者:陈哲Gilbert
出处:http://gilbert.cnblogs.com
版权声明:
本文版权归作者所有,欢迎转载,请在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。