AES加密解密

作者:追风剑情 发布于:2021-10-20 11:36 分类:C#

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);
    }
}

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号