AES加解密帮助类

9

title: AES加密帮助类
description:
published: true
date: 2024-11-16T00:57:14.878Z
tags:
editor: markdown

dateCreated: 2024-11-16T00:57:14.878Z

AES加密帮助类

public class AesHelper
{
    // AES加密
    public static string EncryptStringToBase64(string plainText, string keyString)
    {
        // 将密钥字符串转换为字节数组
        byte[] keyBytes = Encoding.UTF8.GetBytes(keyString);

        // 创建AES对象
        using (Aes aesAlg = Aes.Create())
        {
            // 设置密钥大小(256位)
            aesAlg.KeySize = 256;
            aesAlg.Key = keyBytes;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            // 生成初始化向量IV
            aesAlg.GenerateIV();

            // 创建加密器对象
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // 创建用于输出的内存流
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                // 将IV添加到加密流的开始
                msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);

                // 创建加密流
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        // 将明文写入加密流
                        swEncrypt.Write(plainText);
                    }
                }

                // 获取加密后的字节数据
                byte[] encrypted = msEncrypt.ToArray();

                // 将加密后的字节数据转换为Base64字符串
                return Convert.ToBase64String(encrypted);
            }
        }
    }

    // AES解密
    public static string DecryptBase64ToString(string cipherTextBase64, string keyString)
    {
        // 将密钥字符串转换为字节数组
        byte[] keyBytes = Encoding.UTF8.GetBytes(keyString);

        // 将Base64字符串转换为字节数组
        byte[] cipherTextBytes = Convert.FromBase64String(cipherTextBase64);

        // 创建AES对象
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.KeySize = 256;
            aesAlg.Key = keyBytes;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            // 从加密数据中提取IV
            byte[] iv = new byte[aesAlg.IV.Length];
            Array.Copy(cipherTextBytes, iv, iv.Length);
            aesAlg.IV = iv;

            // 创建解密器对象
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            // 创建用于解密的内存流
            using (MemoryStream msDecrypt = new MemoryStream(cipherTextBytes, iv.Length, cipherTextBytes.Length - iv.Length))
            {
                // 创建解密流
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        // 读取解密后的字符串
                        return srDecrypt.ReadToEnd();
                    }
                }
            }
        }
    }
}


class Program
{
    static void Main()
    {
        // 示例JSON字符串
        string jsonString = "{\"name\":\"John\", \"age\":30}";

        // 密钥(必须是32个字符,对应256位密钥大小)
        string key = "12345678901234567890123456789012";

        //加密后的字符串
        string encryptedBase64 = "";

        try
        {
            // 加密JSON字符串
            encryptedBase64 = AesHelper.EncryptStringToBase64(jsonString, key);

            // 输出加密后的Base64字符串
            Console.WriteLine("Encrypted (Base64): " + encryptedBase64);
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: " + e.Message);
        }

        try
        {
            // 解密Base64字符串
            string decryptedString = AesHelper.DecryptBase64ToString(encryptedBase64, key);

            // 输出解密后的字符串
            Console.WriteLine("Decrypted: " + decryptedString);
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: " + e.Message);
        }

    }
}