256位AES加密和解密

时间:2021-12-26 21:10:10
 1  /// <summary>  
 2         /// 256位AES加密  
 3         /// </summary>  
 4         /// <param name="toEncrypt"></param>  
 5         /// <returns></returns> 
 6         public static string Encrypt(string toEncrypt, string skey, string IV)
 7         {
 8             //256-AES key      
 9             //byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678123456781234567812345678");
10             byte[] keyArray = UTF8Encoding.UTF8.GetBytes(skey);
11             byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
12             byte[] ivArray = UTF8Encoding.UTF8.GetBytes(IV);//1234567812345678
13 
14             RijndaelManaged rDel = new RijndaelManaged();
15             rDel.Key = keyArray;
16             rDel.Mode = CipherMode.CBC;
17             rDel.Padding = PaddingMode.PKCS7;
18             rDel.IV = ivArray;
19 
20             ICryptoTransform cTransform = rDel.CreateEncryptor();
21             byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
22 
23             return Convert.ToBase64String(resultArray, 0, resultArray.Length);
24         }
 /// <summary>  
        /// 256位AES解密  
        /// </summary>  
        /// <param name="toDecrypt"></param>  
        /// <returns></returns>  
        public static string Decrypt(string toDecrypt, string skey, string IV)
        {
            //256-AES key
            //byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678123456781234567812345678");
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(skey);
            byte[] toDecryptArray = Convert.FromBase64String(toDecrypt);
            byte[] ivArray = UTF8Encoding.UTF8.GetBytes(IV); //1234567812345678

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.PKCS7;
            rDel.IV = ivArray;

            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);

            return UTF8Encoding.UTF8.GetString(resultArray);
        }