AES加密解密 助手类 CBC加密模式


string str = "2018";
string result1 = AESHelper.AesEncrypt(str);
string result2 = AESHelper.AesDecrypt(result1);
namespace Demo
{
    /// 
    /// AES加密解密 助手类
    /// CBC加密模式
    /// 
    public class AESHelper
    {
        /// 
        /// 默认密钥-长度32位
        /// 
        private const string Key = "32位";

        /// 
        /// 默认向量-长度16位
        /// 
        private const string Iv = "16位";


        ///   
        /// AES加密  
        ///   
        /// 需要加密字符串  
        /// 加密后字符串 
        public static string AesEncrypt(string str)
        {
            return Encrypt(str, Key);
        }

        ///   
        /// AES解密  
        ///   
        /// 需要解密字符串  
        /// 解密后字符串  
        public static string AesDecrypt(string str)
        {
            return Decrypt(str, Key);
        }


        /// 
        ///  AES 加密
        /// 
        /// 明文(待加密)
        /// 密文
        /// 
        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);
        }
        /// 
        ///  AES 解密
        /// 
        /// 明文(待解密)
        /// 密文
        /// 
        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