59 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			C#
		
	
	
	
			
		
		
	
	
			59 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			C#
		
	
	
	
using System.Security.Cryptography;
 | 
						|
using System.Text;
 | 
						|
 | 
						|
namespace LY.App.Common.Cypher
 | 
						|
{
 | 
						|
    public class AESCypherUtil
 | 
						|
    {
 | 
						|
        /// <summary>
 | 
						|
        ///  AES 加密
 | 
						|
        /// </summary>
 | 
						|
        /// <param name="str">明文</param>
 | 
						|
        /// <param name="key">密钥对</param>
 | 
						|
        /// <returns>密文</returns>
 | 
						|
        public static string Encrypt(string str, string key, string iv)
 | 
						|
        {
 | 
						|
            using (var aes = Aes.Create())
 | 
						|
            {
 | 
						|
                aes.Key = Encoding.UTF8.GetBytes(key);
 | 
						|
                aes.IV = Encoding.UTF8.GetBytes(iv);
 | 
						|
                aes.Mode = CipherMode.CBC;
 | 
						|
                aes.Padding = PaddingMode.PKCS7;
 | 
						|
 | 
						|
                byte[] strbuffer = Encoding.UTF8.GetBytes(str);
 | 
						|
 | 
						|
                using (var crytTransform = aes.CreateEncryptor(aes.Key, aes.IV))
 | 
						|
                {
 | 
						|
                    byte[] buffer = crytTransform.TransformFinalBlock(strbuffer, 0, strbuffer.Length);
 | 
						|
                    return Convert.ToBase64String(buffer, 0, buffer.Length);
 | 
						|
                }
 | 
						|
            }
 | 
						|
        }
 | 
						|
 | 
						|
        /// <summary>
 | 
						|
        ///  AES 解密
 | 
						|
        /// </summary>
 | 
						|
        /// <param name="str">密文</param>
 | 
						|
        /// <param name="key">密钥对</param>
 | 
						|
        /// <returns>明文</returns>
 | 
						|
        public static string Decrypt(string str, string key, string iv)
 | 
						|
        {
 | 
						|
            using (var aes = Aes.Create())
 | 
						|
            {
 | 
						|
                aes.Key = Encoding.UTF8.GetBytes(key);
 | 
						|
                aes.IV = Encoding.UTF8.GetBytes(iv);
 | 
						|
                aes.Mode = CipherMode.CBC;
 | 
						|
                aes.Padding = PaddingMode.PKCS7;
 | 
						|
 | 
						|
                byte[] strbuffer = System.Convert.FromBase64String(str);
 | 
						|
 | 
						|
                using (var crytTransform = aes.CreateDecryptor(aes.Key, aes.IV))
 | 
						|
                {
 | 
						|
                    byte[] buffer = crytTransform.TransformFinalBlock(strbuffer, 0, strbuffer.Length);
 | 
						|
                    return Encoding.UTF8.GetString(buffer);
 | 
						|
                }
 | 
						|
            }
 | 
						|
        }
 | 
						|
    }
 | 
						|
}
 |