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));
相关推荐
码界奇点13 小时前
Java设计模式精讲从基础到实战的常见模式解析
java·开发语言·设计模式·java-ee·软件工程
四维碎片13 小时前
【Qt】配置安卓开发环境
android·开发语言·qt
西游音月14 小时前
(7)框架搭建:Qt实战项目之主窗体导航栏、状态栏
开发语言·qt
3***499614 小时前
Swift Experience
开发语言·ios·swift
iFlow_AI14 小时前
iFlow CLI Hooks 「从入门到实战」应用指南
开发语言·前端·javascript·人工智能·ai·iflow·iflow cli
Maybyy14 小时前
Chart.js图标绘制工具库
开发语言·javascript·ecmascript
1***s63214 小时前
Python爬虫反爬策略,User-Agent与代理IP
开发语言·爬虫·python
柒儿吖14 小时前
Qt for HarmonyOS 水平进度条组件开发实战
开发语言·qt·harmonyos
咖啡の猫15 小时前
Python的自述
开发语言·python
Charles_go16 小时前
41、C#什么是单例设计模式
java·设计模式·c#