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));
相关推荐
侃侃_天下4 小时前
最终的信号类
开发语言·c++·算法
echoarts4 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix4 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz4 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题5 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说5 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔6 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号6 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_6 小时前
QT(4)
开发语言·汇编·c++·qt·算法
Brookty6 小时前
【JavaEE】线程安全-内存可见性、指令全排序
java·开发语言·后端·java-ee·线程安全·内存可见性·指令重排序