我正在使用类似这样的代码来加密文件。
FileStream fsInput = new FileStream(ifile_path,
FileMode.Open,
FileAccess.Read);
FileStream fsEncrypted = new FileStream(ofile_path,
FileMode.Create,
FileAccess.Write);
AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
AES.Mode = CipherMode.CBC;
AES.KeySize = 256;
iv = AES.IV;
AES.Key = key;
ICryptoTransform aesencrypt = AES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted,
aesencrypt,
CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
但是,虽然此代码成功加密了 .txt 和 .xml 文件,但它不适用于其他文件类型,例如 .docx 或图像文件格式。我可以对代码进行哪些更改以将功能扩展到所有此类文件类型?
最佳答案
您想使用 BinaryReader 和 BinaryWriter 来执行文件 I/O。普通 StreamReader 将尝试使用特定编码读取字节,因为它实现了 TextReader 并将破坏原始数据类型。这就是为什么纯文本 .txt 和 .xml 有效而 .docx 文件无效的原因。
关于c# - 使用 AES 加密任何文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23374121/