软件编程
位置:首页>> 软件编程>> C#编程>> c# AES字节数组加密解密流程及代码实现

c# AES字节数组加密解密流程及代码实现

作者:syzcyyx  发布时间:2021-12-11 21:44:20 

标签:c#,aes,加密,解密

AES类时微软MSDN中最常用的加密类,微软官网也有例子,参考链接:https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.aes?view=netframework-4.8
但是这个例子并不好用,限制太多,通用性差,实际使用中,我遇到的更多情况需要是这样:
1、输入一个字节数组,经AES加密后,直接输出加密后的字节数组。
2、输入一个加密后的字节数组,经AES解密后,直接输出原字节数组。

对于我这个十八流业余爱好者来说,AES我是以用为主的,所以具体的AES是怎么运算的,我其实并不关心,我更关心的是AES的处理流程。结果恰恰这一方面,网上的信息差强人意,看了网上不少的帖子,但感觉都没有说完整说透,而且很多帖子有错误。

因此,我自己绘制了一张此种方式下的流程图:

c# AES字节数组加密解密流程及代码实现

按照此流程图进行了核心代码的编写,验证方法AesCoreSingleTest既是依照此流程的产物,实例化类AesCoreSingle后调用此方法即可验证。

至于类中的异步方法EnOrDecryptFileAsync,则是专门用于文件加解密的处理,此异步方法参考自《C# 6.0学习笔记》(周家安 著)最后的示例,这本书写得真棒。


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace AesSingleFile
{
 class AesCoreSingle
 {
   /// <summary>
   /// 使用用户口令,生成符合AES标准的key和iv。
   /// </summary>
   /// <param name="password">用户输入的口令</param>
   /// <returns>返回包含密钥和向量的元组</returns>
   private (byte[] Key, byte[] IV) GenerateKeyAndIV(string password)
   {
     byte[] key = new byte[32];
     byte[] iv = new byte[16];
     byte[] hash = default;
     if (string.IsNullOrWhiteSpace(password))
       throw new ArgumentException("必须输入口令!");
     using (SHA384 sha = SHA384.Create())
     {
       byte[] buffer = Encoding.UTF8.GetBytes(password);
       hash = sha.ComputeHash(buffer);
     }
     //用SHA384的原因:生成的384位哈希值正好被分成两段使用。(32+16)*8=384。
     Array.Copy(hash, 0, key, 0, 32);//生成256位密钥(32*8=256)
     Array.Copy(hash, 32, iv, 0, 16);//生成128位向量(16*8=128)
     return (Key: key, IV: iv);
   }

public byte[] EncryptByte(byte[] buffer, string password)
   {
     byte[] encrypted;
     using (Aes aes = Aes.Create())
     {
       //设定密钥和向量
       (aes.Key, aes.IV) = GenerateKeyAndIV(password);
       //设定运算模式和填充模式
       aes.Mode = CipherMode.CBC;//默认
       aes.Padding = PaddingMode.PKCS7;//默认
       //创建加密器对象(加解密方法不同处仅仅这一句话)
       var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
       using (MemoryStream msEncrypt = new MemoryStream())
       {
         using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))//选择Write模式
         {
           csEncrypt.Write(buffer, 0, buffer.Length);//对原数组加密并写入流中
           csEncrypt.FlushFinalBlock();//使用Write模式需要此句,但Read模式必须要有。
           encrypted = msEncrypt.ToArray();//从流中写入数组(加密之后,数组变长,详见方法AesCoreSingleTest内容)
         }
       }
     }
     return encrypted;
   }
   public byte[] DecryptByte(byte[] buffer, string password)
   {
     byte[] decrypted;
     using (Aes aes = Aes.Create())
     {
       //设定密钥和向量
       (aes.Key, aes.IV) = GenerateKeyAndIV(password);
       //设定运算模式和填充模式
       aes.Mode = CipherMode.CBC;//默认
       aes.Padding = PaddingMode.PKCS7;//默认
       //创建解密器对象(加解密方法不同处仅仅这一句话)
       var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
       using (MemoryStream msDecrypt = new MemoryStream(buffer))
       {
         using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))//选择Read模式
         {
           byte[] buffer_T = new byte[buffer.Length];/*--s1:创建临时数组,用于包含可用字节+无用字节--*/

int i = csDecrypt.Read(buffer_T, 0, buffer.Length);/*--s2:对加密数组进行解密,并通过i确定实际多少字节可用--*/

//csDecrypt.FlushFinalBlock();//使用Read模式不能有此句,但write模式必须要有。

decrypted = new byte[i];/*--s3:创建只容纳可用字节的数组--*/

Array.Copy(buffer_T, 0, decrypted, 0, i);/*--s4:从bufferT拷贝出可用字节到decrypted--*/
         }
       }
       return decrypted;
     }
   }
   public byte[] EnOrDecryptByte(byte[] buffer, string password, ActionDirection direction)
   {
     if (buffer == null)
       throw new ArgumentNullException("buffer为空");
     if (password == null || password == "")
       throw new ArgumentNullException("password为空");
     if (direction == ActionDirection.EnCrypt)
       return EncryptByte(buffer, password);
     else
       return DecryptByte(buffer, password);
   }
   public enum ActionDirection//该枚举说明是加密还是解密
   {
     EnCrypt,//加密
     DeCrypt//解密
   }
   public static void AesCoreSingleTest(string s_in, string password)//验证加密解密模块正确性方法
   {
     byte[] buffer = Encoding.UTF8.GetBytes(s_in);
     AesCoreSingle aesCore = new AesCoreSingle();
     byte[] buffer_ed = aesCore.EncryptByte(buffer, password);
     byte[] buffer_ed2 = aesCore.DecryptByte(buffer_ed, password);
     string s = Encoding.UTF8.GetString(buffer_ed2);
     string s2 = "下列字符串\n" + s + '\n' + $"原buffer长度 → {buffer.Length}, 加密后buffer_ed长度 → {buffer_ed.Length}, 解密后buffer_ed2长度 → {buffer_ed2.Length}";
     MessageBox.Show(s2);
     /* 字符串在加密前后的变化(默认CipherMode.CBC运算模式, PaddingMode.PKCS7填充模式)
      * 1、如果数组长度为16的倍数,则加密后的数组长度=原长度+16
       如对于下列字符串
       D:\User\Documents\Administrator - DOpus Config - 2020-06-301.ocb
       使用UTF8编码转化为字节数组后,
       原buffer → 64, 加密后buffer_ed → 80, 解密后buffer_ed2 → 64
      * 2、如果数组长度不为16的倍数,则加密后的数组长度=16倍数向上取整
       如对于下列字符串
       D:\User\Documents\cc_20200630_113921.reg
       使用UTF8编码转化为字节数组后
       原buffer → 40, 加密后buffer_ed → 48, 解密后buffer_ed2 → 40
       参考文献:
       1-《AES补位填充PaddingMode.Zeros模式》http://blog.chinaunix.net/uid-29641438-id-5786927.html
       2-《关于PKCS5Padding与PKCS7Padding的区别》https://www.cnblogs.com/midea0978/articles/1437257.html
       3-《AES-128 ECB 加密有感》http://blog.sina.com.cn/s/blog_60cf051301015orf.html
      */
   }

/***---声明CancellationTokenSource对象--***/
   private CancellationTokenSource cts;//using System.Threading;引用
   public Task EnOrDecryptFileAsync(Stream inStream, long inStream_Seek, Stream outStream, long outStream_Seek, string password, ActionDirection direction, IProgress<int> progress)
   {
     /***---实例化CancellationTokenSource对象--***/
     cts?.Dispose();//cts为空,不动作,cts不为空,执行Dispose。
     cts = new CancellationTokenSource();

Task mytask = new Task(
       () =>
       {
         EnOrDecryptFile(inStream, inStream_Seek, outStream, outStream_Seek, password, direction, progress);
       }, cts.Token, TaskCreationOptions.LongRunning);
     mytask.Start();
     return mytask;
   }
   public void EnOrDecryptFile(Stream inStream, long inStream_Seek, Stream outStream, long outStream_Seek, string password, ActionDirection direction, IProgress<int> progress)
   {
     if (inStream == null || outStream == null)
       throw new ArgumentException("输入流与输出流是必须的");
     //--调整流的位置(通常是为了避开文件头部分)
     inStream.Seek(inStream_Seek, SeekOrigin.Begin);
     outStream.Seek(outStream_Seek, SeekOrigin.Begin);
     //用于记录处理进度
     long total_Length = inStream.Length - inStream_Seek;
     long totalread_Length = 0;
     //初始化报告进度
     progress.Report(0);

using (Aes aes = Aes.Create())
     {
       //设定密钥和向量
       (aes.Key, aes.IV) = GenerateKeyAndIV(password);
       //创建加密器解密器对象(加解密方法不同处仅仅这一句话)
       ICryptoTransform cryptor;
       if (direction == ActionDirection.EnCrypt)
         cryptor = aes.CreateEncryptor(aes.Key, aes.IV);
       else
         cryptor = aes.CreateDecryptor(aes.Key, aes.IV);
       using (CryptoStream cstream = new CryptoStream(outStream, cryptor, CryptoStreamMode.Write))
       {
         byte[] buffer = new byte[512 * 1024];//每次读取512kb的数据
         int readLen = 0;
         while ((readLen = inStream.Read(buffer, 0, buffer.Length)) != 0)
         {
           // 向加密流写入数据
           cstream.Write(buffer, 0, readLen);
           totalread_Length += readLen;
           //汇报处理进度
           if (progress != null)
           {
             long per = 100 * totalread_Length / total_Length;
             progress.Report(Convert.ToInt32(per));
           }
         }
       }
     }
   }
 }
}

来源:https://www.cnblogs.com/syzcyyx/p/13657222.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com