鸟语天空
AES加密解密
post by:追风剑情 2021-10-20 11:36
using System;
using System.Text;
using System.Security.Cryptography;
/// <summary>
/// AES加密/解密
/// </summary>
public sealed class AESCrypto
{
    //一个256位的默认key
    private const string DEFAULT_KEY = "AbcdefG@1234567*QWERTYU-Mnbvcxz#";

    //加密
    public static string Encrypt(string encryptString, string encryptKey = "")
    {
        if (string.IsNullOrEmpty(encryptString))
            return string.Empty;

        if (string.IsNullOrEmpty(encryptKey))
            encryptKey = DEFAULT_KEY;

        byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptString);
        RijndaelManaged rm = new RijndaelManaged
        {
            Key = Encoding.UTF8.GetBytes(encryptKey),
            Mode = CipherMode.ECB,//最简单的分块加密
            Padding = PaddingMode.PKCS7
        };

        ICryptoTransform cTransform = rm.CreateEncryptor();
        Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

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

    //解密
    public static string Decrypt(string decryptString, string decryptKey = "")
    {
        if (string.IsNullOrEmpty(decryptString)) 
            return string.Empty;

        if (string.IsNullOrEmpty(decryptKey))
            decryptKey = DEFAULT_KEY;

        Byte[] toEncryptArray = Convert.FromBase64String(decryptString);
        RijndaelManaged rm = new RijndaelManaged
        {
            Key = Encoding.UTF8.GetBytes(decryptKey),
            Mode = CipherMode.ECB,
            Padding = PaddingMode.PKCS7
        };

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

        return Encoding.UTF8.GetString(resultArray);
    }
}
评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容