From f0acc4d5ebabb31e96a9be2bab3b10cfbe707271 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9B=A8=7E?= Date: Mon, 16 Apr 2018 11:17:05 +0800 Subject: [PATCH] Add aes encrypt and decrypt with file. --- test/NETCore.Encrypt.Tests/AES_Tests.cs | 47 +++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/test/NETCore.Encrypt.Tests/AES_Tests.cs b/test/NETCore.Encrypt.Tests/AES_Tests.cs index 5dd0699..f9f015f 100644 --- a/test/NETCore.Encrypt.Tests/AES_Tests.cs +++ b/test/NETCore.Encrypt.Tests/AES_Tests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Text; using Xunit; @@ -187,5 +188,51 @@ public void Aes_Decrypt_With_ErrorIV_Fail_Test() //Assert Assert.Throws(() => EncryptProvider.AESDecrypt(srcString, key, iv)); } + + [Fact(DisplayName = "AES encrypt and decrypt about file stream")] + public void Aes_File_Test() + { + var rootDir = Path.Combine(AppContext.BaseDirectory, "Assets"); + if (!Directory.Exists(rootDir)) + { + Directory.CreateDirectory(rootDir); + } + + var file = Path.Combine(rootDir, "AES_File_Test.txt"); + if (!File.Exists(file)) + { + using (var fileStream = File.OpenWrite(file)) + { + var tempDatas = Encoding.UTF8.GetBytes("May be you shoud get all the buffer of file,and then decrypt by EncryptProvider."); + fileStream.Write(tempDatas, 0, tempDatas.Length); + } + } + + var aesKey = EncryptProvider.CreateAesKey(); + + //encrypt + var text = File.ReadAllText(file); + var datas = File.ReadAllBytes(file); + + var encryptedDatas = EncryptProvider.AESEncrypt(datas, aesKey.Key, aesKey.IV); + var encryptedFile = Path.Combine(rootDir, "AES_File_Test_Encrypted.txt"); + + using (var fileStream = File.OpenWrite(encryptedFile)) + { + fileStream.Write(encryptedDatas, 0, encryptedDatas.Length); + } + + //decrypt + var encryptedFileDatas = File.ReadAllBytes(encryptedFile); + var decryptedDatas = EncryptProvider.AESDecrypt(encryptedFileDatas, aesKey.Key, aesKey.IV); + + var decryptedText = Encoding.UTF8.GetString(decryptedDatas); + + //assert + Assert.NotNull(decryptedDatas); + Assert.Equal(decryptedText, text); + + + } } }