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));
相关推荐
厦门德仔3 分钟前
【C#】C#字符串拼接的6种方式及其性能分析对比
服务器·windows·c#
天天进步20157 分钟前
Python项目-基于Flask的个人博客系统设计与实现(1)
开发语言·python·flask
安然无虞9 分钟前
31天Python入门——第20天:魔法方法详解
开发语言·后端·爬虫·python
QQ__176461982413 分钟前
Matlab安装tdms插件
开发语言·matlab·tdms插件
画个逗号给明天"15 分钟前
C#从入门到精通(5)
开发语言·笔记·c#
赤秀39 分钟前
C++模板初阶
开发语言·c++
橘猫云计算机设计1 小时前
基于JavaWeb的二手图书交易系统(源码+lw+部署文档+讲解),源码可白嫖!
java·开发语言·前端·毕业设计·php
半桔1 小时前
红黑树剖析
c语言·开发语言·数据结构·c++·后端·算法
江烽渔火1 小时前
C++ 多态
开发语言·c++
m0_490240671 小时前
软件自动化测试(1):python+selenium自动化测试环境搭建
开发语言·python·selenium