C# aes加密解密byte数组

cs 复制代码
using System.Security.Cryptography;
using System.Text;

namespace AESStu01;

public class AesHelper
{
    // AES加密密钥和向量(需要保密)  
    private static readonly string Key = "";//16长度字符串+数字混合

    private static readonly string IV = "";//16长度字符串+数字混合

    // 加密字节数组  
    public static byte[] Encrypt(byte[] plainBytes)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Encoding.UTF8.GetBytes(Key);
            aesAlg.IV = Encoding.UTF8.GetBytes(IV);

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    csEncrypt.Write(plainBytes, 0, plainBytes.Length);
                    csEncrypt.Close();
                }

                return msEncrypt.ToArray();
            }
        }
    }

    // 解密字节数组  
    public static byte[] Decrypt(byte[] cipherBytes)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Encoding.UTF8.GetBytes(Key);
            aesAlg.IV = Encoding.UTF8.GetBytes(IV);
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream())
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
                {
                    csDecrypt.Write(cipherBytes, 0, cipherBytes.Length);
                    csDecrypt.Close();
                }

                return msDecrypt.ToArray();
            }
        }
    }
}

测试

cs 复制代码
using AESStu01;

var orginData = new byte[]
{
    1, 2, 3, 4, 5
};
Console.WriteLine("AES加密");
var enData = AesHelper.Encrypt(orginData);
Console.WriteLine("加密后的的数据");
Console.WriteLine(string.Join(",",enData));
var deData = AesHelper.Decrypt(enData);
Console.WriteLine("解密后的的数据");
Console.WriteLine(string.Join(",",deData));
相关推荐
小禾苗_1 小时前
C++ ——继承
开发语言·c++
李长渊哦1 小时前
Java 虚拟机(JVM)方法区详解
java·开发语言·jvm
进击ing小白1 小时前
Qt程序退出相关资源释放问题
开发语言·qt
烂蜻蜓2 小时前
前端已死?什么是前端
开发语言·前端·javascript·vue.js·uni-app
老猿讲编程2 小时前
安全C语言编码规范概述
c语言·开发语言·安全
软件黑马王子5 小时前
Unity游戏制作中的C#基础(5)条件语句和循环语句知识点全解析
游戏·unity·c#
shepherd枸杞泡茶5 小时前
第3章 3.3日志 .NET Core日志 NLog使用教程
c#·asp.net·.net·.netcore
Biomamba生信基地5 小时前
两天入门R语言,周末开讲
开发语言·r语言·生信
RAN_PAND5 小时前
STL介绍1:vector、pair、string、queue、map
开发语言·c++·算法
Bio Coder5 小时前
R语言安装生物信息数据库包
开发语言·数据库·r语言