ASP.NET AES暗号化

1912 ワード

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;


namespace Utility
{
    /// <summary>
    /// AES    
    /// </summary>
    public class AES
    {
        public AES() { }


        private static string key = "fds;lj098lkr#@%$#^hKLJHL89435dfsf90U90";


        #region AES  
        public static string Encrypt(string toEncrypt)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);


            RijndaelManaged rDel = new RijndaelManaged();//using System.Security.Cryptography;   
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;//using System.Security.Cryptography;   
            rDel.Padding = PaddingMode.PKCS7;//using System.Security.Cryptography;   


            ICryptoTransform cTransform = rDel.CreateEncryptor();//using System.Security.Cryptography;   
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        #endregion AES  




        #region AES  
        public static string Decrypt(string toDecrypt)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);


            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;


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


            return UTF8Encoding.UTF8.GetString(resultArray);
        }
        #endregion AES     
    }
}