C# AES 加解密处理

引言

  这是一个有关AES加解密的方法类

一、设置AES加解密密钥:下面列出自己分配的三类密钥

        private const string UserKey = "roshan-2015-user"; //加密用户名和密码
        private static readonly byte[] UserIv = { 5, 4, 0xF, 7, 9, 0xC, 1, 0xB, 3, 0x5B, 0xD, 0x17, 1, 0xA, 6, 8 };

        private const string ServerAuthTokenKey = "roshan2015server"; //加密服务端AuthToken
        private static readonly byte[] ServerAuthTokenIv = { 0xC, 1, 0xB, 3, 0x5B, 0xD, 5, 4, 0xF, 7, 9, 0x17, 1, 0xA, 6, 8 };

        private const string ClientAuthTokenKey = "roshan2015client";//加密客户端AuthToken
        private static readonly byte[] ClientAuthTokenIv = { 0x38, 0x31, 0x37, 0x34, 0x36, 0x33, 0x35, 0x33, 0x32, 0x31, 0x34, 0x38, 0x37, 0x36, 0x35, 0x32 };   
密钥设置

二、填充方法:这里个人采用默认的填充方法

Mode:CBC

Padding:PKCS7

三、配置加解密方法

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="toEncrypt">明文</param>
        /// <param name="key">秘钥</param>
        /// <param name="ivBytes">向量</param>
        /// <returns>密文</returns>
        public static string AESEncrypt(string toEncrypt, string key, byte[] ivBytes)
        {
            byte[] toEncryptBytes = System.Text.Encoding.UTF8.GetBytes(toEncrypt);
            var rijndael = new RijndaelManaged();
            rijndael.Key = System.Text.Encoding.UTF8.GetBytes(key);
            rijndael.IV = ivBytes;
            ICryptoTransform cryptoTransform = rijndael.CreateDecryptor();
            byte[] resultBytes = cryptoTransform.TransformFinalBlock(toEncryptBytes, 0, toEncryptBytes.Length);
            return Convert.ToBase64String(resultBytes);
        }
加密方法
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="toDecrypt">密文</param>
        /// <param name="key">秘钥</param>
        /// <param name="ivBytes">向量</param>
        /// <returns>明文</returns>
        private static string AESDecrypt(string toDecrypt, string key, byte[] ivBytes)
        {
            byte[] toDecryptBytes = Convert.FromBase64String(toDecrypt);
            var rijndael = new RijndaelManaged();
            rijndael.Key = System.Text.Encoding.UTF8.GetBytes(key);
            rijndael.IV = ivBytes;
            ICryptoTransform cryptoTransform = rijndael.CreateDecryptor();
            byte[] resultArray = cryptoTransform.TransformFinalBlock(toDecryptBytes, 0, toDecryptBytes.Length);
            return System.Text.Encoding.UTF8.GetString(resultArray);
        }
解密方法

 

posted @ 2016-04-12 10:02  JaminHuang  阅读(2942)  评论(0编辑  收藏  举报