c# - 使用 AES 加密任何文件

标签 c# encryption aes

我正在使用类似这样的代码来加密文件。

            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/

相关文章:

Java - 使用数组中的值的replace()方法正在更改数组值?

javascript - Crypto-js 本地端到 php 服务器端

c# - 将时间四舍五入到最接近的小时

c# - GPS计算Windows Phone 7上两点之间的距离

c# - 在表单中处理自定义内存中控件

c# - 解压缩 gzipstream 时出错——GZip header 中的魔数(Magic Number)不正确

php - 如何使用特定于使用的 key 创建两种编码/解码方法 - PHP?

.net - 加密 web.config 毫无意义吗?

encryption - 加密 AES key ?

java - BadPaddingException 使用 AES 算法解密 java