c# - 使用 AES/Rijndael 将文件加密为 Base64 格式
问题描述
在 DevGlan 中,在https://www.devglan.com/online-tools/aes-encryption-decryption有一个在线工具,您可以在其中上传文件,然后使用 AES 加密将其加密为 Base64 格式,并选择一个密码模式、密钥和初始化向量。我想在我的 C# Web 应用程序中实现同样的目标。这是我的代码:
FileUpload3.SaveAs(Server.MapPath(FileUpload3.FileName));
string inputFile = Server.MapPath(FileUpload3.FileName);
byte[] bytesToEncrypt = File.ReadAllBytes(inputFile);
byte[] encryptedBytes = EncryptAESfile(bytesToEncrypt, CipherMode.CBC, keyArray, IV);
string encryptedFileBase64 = Convert.ToBase64String(encryptedBytes);
string encryptedFileHex = BitConverter.ToString(encryptedBytes).Replace("-", "");
public byte[] EncryptAESfile(byte[] data, CipherMode mode, byte[] key, byte[] iv)
{
byte[] encryptedData = null;
if (data == null)
throw new ArgumentNullException("data");
if (data == key)
throw new ArgumentNullException("key");
if (data == iv)
throw new ArgumentNullException("iv");
using (RijndaelManaged aesAlg = new RijndaelManaged())
{
aesAlg.Key = key;
aesAlg.IV = iv;
aesAlg.Mode = mode;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);
}
return encryptedData;
}
该代码确实返回了文件的 Base64 字符串,如变量 中一样encryptedFileBase64
,但不是引用 DevGlan 的正确字符串。我的代码只返回一个长度为 24 的 Base64 字符串,而 DevGlan 返回一个近 100,000 个字符的字符串。此外,当我测试是否正在读取字节时,以下代码返回 0,因此问题可能出在我的前几行:
lblBytes.Text += "Bytes read: " + bytesToEncrypt.Length;
我还看到了许多加密文件的例子——无论是在 AES 还是其他一些对称加密算法中——但不是那些返回 Base64 字符串的例子。大多数在 CryptoStream 关闭之前以这样的行结束:
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length); // The input FileStream
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
有没有办法读取 CryptoStream 的字节数组,然后将其转换为 Base64,因为我看不到bytearrayinput
单独存储正确的信息。帮助将不胜感激。谢谢!
解决方案
第一:密钥是如何创建的?你有没有仔细检查过你的盐是一样的?
我也没有检查过,但是这段代码应该可以工作:
AesManaged cipher = new AesManaged();
cipher.Mode = MODE;
ICryptoTransform encryptor = cipher.CreateEncryptor(KEY, IV);
MemoryStream to = new MemoryStream();
CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write);
writer.Write(input, 0, input.Length);
writer.FlushFinalBlock();
byte[] encrypted = to.ToArray();
return Convert.ToBase64String(encrypted);
推荐阅读
- ios - Is there a better way to remove all annotations from PDF document?
- laravel - 使用 element-ui 向表单动态添加字段
- highcharts - 在 Highcharts 中显示标签栈 Label
- r - as.Date() 从一年中的一天计算中给出错误的输出
- javascript - 获取 jQuery Datatables 中选中的所有复选框的值
- python - 从单个 monorepo 引用多个 Django 项目
- json - 使用 JSON 解组 map[string]int64 的 Go 中的问题
- string - 在Golang中改变一个字符串?
- javascript - 是否有纯 HTML5/Javascript 替代 jQuery.Callbacks() 来实现客户端发布/订阅?
- javascript - 从另一台计算机或手机添加数据后,如何更新计算机上的视图?