【发布时间】:2016-10-25 12:44:06
【问题描述】:
我正在使用 aes 密码术来加密文件。
private static void Encrypt(string inputFilePath, string outputfilePath)
{
string EncryptionKey = "MAKV2SPBNI99212";
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
{
using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
//int data;
//while ((data = fsInput.ReadByte()) != -1)
//{
// cs.WriteByte((byte)data);
//}
byte[] bytes = new byte[fsInput.Length];
while (fsInput.Read(bytes, 0, (int)fsInput.Length) > 0) ;
cs.Write(bytes, 0, bytes.Length);
}
}
}
}
}
private static void Decrypt(string inputFilePath, string outputfilePath)
{
string EncryptionKey = "MAKV2SPBNI99212";
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
{
using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
{
//int data;
//while ((data = cs.ReadByte()) != -1)
//{
// fsOutput.WriteByte((byte)data);
//}
byte[] bytes = new byte[fsInput.Length];
while (cs.Read(bytes, 0, (int)fsInput.Length) > 0) ;
fsOutput.Write(bytes, 0, bytes.Length);
}
}
}
}
}
在主函数中我加密、解密word文件:
Encrypt(@"E:\test.docx", @"E:\test.enc");
Decrypt(@"E:\test.enc", @"E:\test_new.docx");
当我使用 ReadByte 函数加密、解密每个字节时。文件 test_new.docx 已创建并正常打开。但是当我使用读取函数加密、解密许多字节时,文件 test_new.docx 被创建但无法打开,错误内容。 有人有想法吗?谢谢!
【问题讨论】:
标签: c# .net encryption cryptography