【发布时间】:2019-12-25 03:48:03
【问题描述】:
在 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);
参考:Encrypting any file using AES
有没有办法读取 CryptoStream 的字节数组,然后将其转换为 Base64,因为我看不到 bytearrayinput 单独存储正确的信息。帮助将不胜感激。谢谢!
【问题讨论】:
-
如果你从输入文件中读取零字节,你肯定需要先解决这个问题。您的其余问题(加密等)甚至都不相关。文件是否存在?
Server.MapPath对它做了什么? -
该文件应该存在 - 因为它是通过 ASP.NET FileUpload 控件上传的,然后 Server.MapPath() 方法将其保存到我的 Azure Web 服务器的根目录,即 D:/home /网站/wwwroot。如果您有兴趣帮助我,我需要弄清楚如何从 FileUpload 控件中获取文件,然后将其放入代码中以通过 Rijndael 对其进行加密。
标签: c# encryption aes rijndael