c# AES字節(jié)數(shù)組加密解密流程及代碼實(shí)現(xiàn)
AES類時(shí)微軟MSDN中最常用的加密類,微軟官網(wǎng)也有例子,參考鏈接:https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.aes?view=netframework-4.8
但是這個(gè)例子并不好用,限制太多,通用性差,實(shí)際使用中,我遇到的更多情況需要是這樣:
1、輸入一個(gè)字節(jié)數(shù)組,經(jīng)AES加密后,直接輸出加密后的字節(jié)數(shù)組。
2、輸入一個(gè)加密后的字節(jié)數(shù)組,經(jīng)AES解密后,直接輸出原字節(jié)數(shù)組。
對(duì)于我這個(gè)十八流業(yè)余愛好者來說,AES我是以用為主的,所以具體的AES是怎么運(yùn)算的,我其實(shí)并不關(guān)心,我更關(guān)心的是AES的處理流程。結(jié)果恰恰這一方面,網(wǎng)上的信息差強(qiáng)人意,看了網(wǎng)上不少的帖子,但感覺都沒有說完整說透,而且很多帖子有錯(cuò)誤。
因此,我自己繪制了一張此種方式下的流程圖:

按照此流程圖進(jìn)行了核心代碼的編寫,驗(yàn)證方法AesCoreSingleTest既是依照此流程的產(chǎn)物,實(shí)例化類AesCoreSingle后調(diào)用此方法即可驗(yàn)證。
至于類中的異步方法EnOrDecryptFileAsync,則是專門用于文件加解密的處理,此異步方法參考自《C# 6.0學(xué)習(xí)筆記》(周家安 著)最后的示例,這本書寫得真棒。
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標(biāo)準(zhǔn)的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())
{
//設(shè)定密鑰和向量
(aes.Key, aes.IV) = GenerateKeyAndIV(password);
//設(shè)定運(yùn)算模式和填充模式
aes.Mode = CipherMode.CBC;//默認(rèn)
aes.Padding = PaddingMode.PKCS7;//默認(rèn)
//創(chuàng)建加密器對(duì)象(加解密方法不同處僅僅這一句話)
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);//對(duì)原數(shù)組加密并寫入流中
csEncrypt.FlushFinalBlock();//使用Write模式需要此句,但Read模式必須要有。
encrypted = msEncrypt.ToArray();//從流中寫入數(shù)組(加密之后,數(shù)組變長,詳見方法AesCoreSingleTest內(nèi)容)
}
}
}
return encrypted;
}
public byte[] DecryptByte(byte[] buffer, string password)
{
byte[] decrypted;
using (Aes aes = Aes.Create())
{
//設(shè)定密鑰和向量
(aes.Key, aes.IV) = GenerateKeyAndIV(password);
//設(shè)定運(yùn)算模式和填充模式
aes.Mode = CipherMode.CBC;//默認(rèn)
aes.Padding = PaddingMode.PKCS7;//默認(rèn)
//創(chuàng)建解密器對(duì)象(加解密方法不同處僅僅這一句話)
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:創(chuàng)建臨時(shí)數(shù)組,用于包含可用字節(jié)+無用字節(jié)--*/
int i = csDecrypt.Read(buffer_T, 0, buffer.Length);/*--s2:對(duì)加密數(shù)組進(jìn)行解密,并通過i確定實(shí)際多少字節(jié)可用--*/
//csDecrypt.FlushFinalBlock();//使用Read模式不能有此句,但write模式必須要有。
decrypted = new byte[i];/*--s3:創(chuàng)建只容納可用字節(jié)的數(shù)組--*/
Array.Copy(buffer_T, 0, decrypted, 0, i);/*--s4:從bufferT拷貝出可用字節(jié)到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)//驗(yàn)證加密解密模塊正確性方法
{
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);
/* 字符串在加密前后的變化(默認(rèn)CipherMode.CBC運(yùn)算模式, PaddingMode.PKCS7填充模式)
* 1、如果數(shù)組長度為16的倍數(shù),則加密后的數(shù)組長度=原長度+16
如對(duì)于下列字符串
D:\User\Documents\Administrator - DOpus Config - 2020-06-301.ocb
使用UTF8編碼轉(zhuǎn)化為字節(jié)數(shù)組后,
原buffer → 64, 加密后buffer_ed → 80, 解密后buffer_ed2 → 64
* 2、如果數(shù)組長度不為16的倍數(shù),則加密后的數(shù)組長度=16倍數(shù)向上取整
如對(duì)于下列字符串
D:\User\Documents\cc_20200630_113921.reg
使用UTF8編碼轉(zhuǎn)化為字節(jié)數(shù)組后
原buffer → 40, 加密后buffer_ed → 48, 解密后buffer_ed2 → 40
參考文獻(xiàn):
1-《AES補(bǔ)位填充PaddingMode.Zeros模式》http://blog.chinaunix.net/uid-29641438-id-5786927.html
2-《關(guān)于PKCS5Padding與PKCS7Padding的區(qū)別》https://www.cnblogs.com/midea0978/articles/1437257.html
3-《AES-128 ECB 加密有感》http://blog.sina.com.cn/s/blog_60cf051301015orf.html
*/
}
/***---聲明CancellationTokenSource對(duì)象--***/
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)
{
/***---實(shí)例化CancellationTokenSource對(duì)象--***/
cts?.Dispose();//cts為空,不動(dòng)作,cts不為空,執(zhí)行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("輸入流與輸出流是必須的");
//--調(diào)整流的位置(通常是為了避開文件頭部分)
inStream.Seek(inStream_Seek, SeekOrigin.Begin);
outStream.Seek(outStream_Seek, SeekOrigin.Begin);
//用于記錄處理進(jìn)度
long total_Length = inStream.Length - inStream_Seek;
long totalread_Length = 0;
//初始化報(bào)告進(jìn)度
progress.Report(0);
using (Aes aes = Aes.Create())
{
//設(shè)定密鑰和向量
(aes.Key, aes.IV) = GenerateKeyAndIV(password);
//創(chuàng)建加密器解密器對(duì)象(加解密方法不同處僅僅這一句話)
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的數(shù)據(jù)
int readLen = 0;
while ((readLen = inStream.Read(buffer, 0, buffer.Length)) != 0)
{
// 向加密流寫入數(shù)據(jù)
cstream.Write(buffer, 0, readLen);
totalread_Length += readLen;
//匯報(bào)處理進(jìn)度
if (progress != null)
{
long per = 100 * totalread_Length / total_Length;
progress.Report(Convert.ToInt32(per));
}
}
}
}
}
}
}
以上就是c# AES字節(jié)數(shù)組加密解密流程及代碼實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于c# AES字節(jié)數(shù)組加密解密的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#中子類調(diào)用父類的實(shí)現(xiàn)方法
這篇文章主要介紹了C#中子類調(diào)用父類的實(shí)現(xiàn)方法,通過實(shí)例逐步分析了類中初始化構(gòu)造函數(shù)的執(zhí)行順序問題,有助于加深對(duì)C#面向?qū)ο蟪绦蛟O(shè)計(jì)的理解,需要的朋友可以參考下2014-09-09
C#如何將Access中以時(shí)間段條件查詢的數(shù)據(jù)添加到ListView中
這篇文章主要介紹了C# 將Access中以時(shí)間段條件查詢的數(shù)據(jù)添加到ListView中,需要的朋友可以參考下2017-07-07
C#簡單訪問SQLite數(shù)據(jù)庫的方法(安裝,連接,查詢等)
這篇文章主要介紹了C#簡單訪問SQLite數(shù)據(jù)庫的方法,涉及SQLite數(shù)據(jù)庫的下載、安裝及使用C#連接、查詢SQLIte數(shù)據(jù)庫的相關(guān)技巧,需要的朋友可以參考下2016-07-07
c# 插入數(shù)據(jù)效率測(cè)試(mongodb)
這篇文章主要介紹了c# 插入數(shù)據(jù)效率測(cè)試(mongodb),插入的速度要比Mysql和sqlserver都要快需要的朋友可以參考下2018-03-03
C# Socket網(wǎng)絡(luò)編程實(shí)例
這篇文章主要介紹了C# Socket網(wǎng)絡(luò)編程實(shí)例,分析了Socket網(wǎng)絡(luò)通信的原理與具體應(yīng)用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-01-01

