1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.IO;4 usingSystem.Linq;5 usingSystem.Security.Cryptography;6 usingSystem.Text;7 usingSystem.Threading;8 usingSystem.Threading.Tasks;9 usingSystem.Windows;10
11 namespaceAesSingleFile12 {13 classAesCoreSingle14 {15 ///
16 ///使用用户口令,生成符合AES标准的key和iv。17 ///
18 /// 用户输入的口令
19 /// 返回包含密钥和向量的元组
20 private (byte[] Key, byte[] IV) GenerateKeyAndIV(stringpassword)21 {22 byte[] key = new byte[32];23 byte[] iv = new byte[16];24 byte[] hash = default;25 if (string.IsNullOrWhiteSpace(password))26 throw new ArgumentException("必须输入口令!");27 using (SHA384 sha =SHA384.Create())28 {29 byte[] buffer =Encoding.UTF8.GetBytes(password);30 hash =sha.ComputeHash(buffer);31 }32 //用SHA384的原因:生成的384位哈希值正好被分成两段使用。(32+16)*8=384。
33 Array.Copy(hash, 0, key, 0, 32);//生成256位密钥(32*8=256)
34 Array.Copy(hash, 32, iv, 0, 16);//生成128位向量(16*8=128)
35 return(Key: key, IV: iv);36 }37
38 public byte[] EncryptByte(byte[] buffer, stringpassword)39 {40 byte[] encrypted;41 using (Aes aes =Aes.Create())42 {43 //设定密钥和向量
44 (aes.Key, aes.IV) =GenerateKeyAndIV(password);45 //设定运算模式和填充模式
46 aes.Mode = CipherMode.CBC;//默认
47 aes.Padding = PaddingMode.PKCS7;//默认48 //创建加密器对象(加解密方法不同处仅仅这一句话)
49 var encryptor =aes.CreateEncryptor(aes.Key, aes.IV);50 using (MemoryStream msEncrypt = newMemoryStream())51 {52 using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))//选择Write模式
53 {54 csEncrypt.Write(buffer, 0, buffer.Length);//对原数组加密并写入流中
55 csEncrypt.FlushFinalBlock();//使用Write模式需要此句,但Read模式必须要有。
56 encrypted = msEncrypt.ToArray();//从流中写入数组(加密之后,数组变长,详见方法AesCoreSingleTest内容)
57 }58 }59 }60 returnencrypted;61 }62 public byte[] DecryptByte(byte[] buffer, stringpassword)63 {64 byte[] decrypted;65 using (Aes aes =Aes.Create())66 {67 //设定密钥和向量
68 (aes.Key, aes.IV) =GenerateKeyAndIV(password);69 //设定运算模式和填充模式
70 aes.Mode = CipherMode.CBC;//默认
71 aes.Padding = PaddingMode.PKCS7;//默认72 //创建解密器对象(加解密方法不同处仅仅这一句话)
73 var decryptor =aes.CreateDecryptor(aes.Key, aes.IV);74 using (MemoryStream msDecrypt = newMemoryStream(buffer))75 {76 using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))//选择Read模式
77 {78 byte[] buffer_T = new byte[buffer.Length];/*--s1:创建临时数组,用于包含可用字节+无用字节--*/
79
80 int i = csDecrypt.Read(buffer_T, 0, buffer.Length);/*--s2:对加密数组进行解密,并通过i确定实际多少字节可用--*/
81
82 //csDecrypt.FlushFinalBlock();//使用Read模式不能有此句,但write模式必须要有。
83
84 decrypted = new byte[i];/*--s3:创建只容纳可用字节的数组--*/
85
86 Array.Copy(buffer_T, 0, decrypted, 0, i);/*--s4:从bufferT拷贝出可用字节到decrypted--*/
87 }88 }89 returndecrypted;90 }91 }92 public byte[] EnOrDecryptByte(byte[] buffer, stringpassword, ActionDirection direction)93 {94 if (buffer == null)95 throw new ArgumentNullException("buffer为空");96 if (password == null || password == "")97 throw new ArgumentNullException("password为空");98 if (direction ==ActionDirection.EnCrypt)99 returnEncryptByte(buffer, password);100 else
101 returnDecryptByte(buffer, password);102 }103 public enum ActionDirection//该枚举说明是加密还是解密
104 {105 EnCrypt,//加密
106 DeCrypt//解密
107 }108 public static void AesCoreSingleTest(string s_in, string password)//验证加密解密模块正确性方法
109 {110 byte[] buffer =Encoding.UTF8.GetBytes(s_in);111 AesCoreSingle aesCore = newAesCoreSingle();112 byte[] buffer_ed =aesCore.EncryptByte(buffer, password);113 byte[] buffer_ed2 =aesCore.DecryptByte(buffer_ed, password);114 string s =Encoding.UTF8.GetString(buffer_ed2);115 string s2 = "下列字符串n" + s + 'n' + $"原buffer长度 → {buffer.Length}, 加密后buffer_ed长度 → {buffer_ed.Length}, 解密后buffer_ed2长度 → {buffer_ed2.Length}";116 MessageBox.Show(s2);117 /*字符串在加密前后的变化(默认CipherMode.CBC运算模式, PaddingMode.PKCS7填充模式)118 * 1、如果数组长度为16的倍数,则加密后的数组长度=原长度+16119 如对于下列字符串120 D:UserDocumentsAdministrator - DOpus Config - 2020-06-301.ocb121 使用UTF8编码转化为字节数组后,122 原buffer → 64, 加密后buffer_ed → 80, 解密后buffer_ed2 → 64123 * 2、如果数组长度不为16的倍数,则加密后的数组长度=16倍数向上取整124 如对于下列字符串125 D:UserDocumentscc_20200630_113921.reg126 使用UTF8编码转化为字节数组后127 原buffer → 40, 加密后buffer_ed → 48, 解密后buffer_ed2 → 40128 参考文献:129 1-《AES补位填充PaddingMode.Zeros模式》http://blog.chinaunix.net/uid-29641438-id-5786927.html
130 2-《关于PKCS5Padding与PKCS7Padding的区别》https://www.cnblogs.com/midea0978/articles/1437257.html
131 3-《AES-128 ECB 加密有感》http://blog.sina.com.cn/s/blog_60cf051301015orf.html
132 */
133 }134
135 /***---声明CancellationTokenSource对象--***/
136 private CancellationTokenSource cts;//using System.Threading;引用
137 public Task EnOrDecryptFileAsync(Stream inStream, long inStream_Seek, Stream outStream, long outStream_Seek, string password, ActionDirection direction, IProgressprogress)138 {139 /***---实例化CancellationTokenSource对象--***/
140 cts?.Dispose();//cts为空,不动作,cts不为空,执行Dispose。
141 cts = newCancellationTokenSource();142
143 Task mytask = newTask(144 () =>
145 {146 EnOrDecryptFile(inStream, inStream_Seek, outStream, outStream_Seek, password, direction, progress);147 }, cts.Token, TaskCreationOptions.LongRunning);148 mytask.Start();149 returnmytask;150 }151 public void EnOrDecryptFile(Stream inStream, long inStream_Seek, Stream outStream, long outStream_Seek, string password, ActionDirection direction, IProgressprogress)152 {153 if (inStream == null || outStream == null)154 throw new ArgumentException("输入流与输出流是必须的");155 //--调整流的位置(通常是为了避开文件头部分)
156 inStream.Seek(inStream_Seek, SeekOrigin.Begin);157 outStream.Seek(outStream_Seek, SeekOrigin.Begin);158 //用于记录处理进度
159 long total_Length = inStream.Length -inStream_Seek;160 long totalread_Length = 0;161 //初始化报告进度
162 progress.Report(0);163
164 using (Aes aes =Aes.Create())165 {166 //设定密钥和向量
167 (aes.Key, aes.IV) =GenerateKeyAndIV(password);168 //创建加密器解密器对象(加解密方法不同处仅仅这一句话)
169 ICryptoTransform cryptor;170 if (direction ==ActionDirection.EnCrypt)171 cryptor =aes.CreateEncryptor(aes.Key, aes.IV);172 else
173 cryptor =aes.CreateDecryptor(aes.Key, aes.IV);174 using (CryptoStream cstream = newCryptoStream(outStream, cryptor, CryptoStreamMode.Write))175 {176 byte[] buffer = new byte[512 * 1024];//每次读取512kb的数据
177 int readLen = 0;178 0, buffer.Length)) != 0)179 {180 //向加密流写入数据
181 cstream.Write(buffer, 0, readLen);182 totalread_Length +=readLen;183 //汇报处理进度
184 if (progress != null)185 {186 long per = 100 * totalread_Length /total_Length;187 progress.Report(Convert.ToInt32(per));188 }189 }190 }191 }192 }193 }194 }