首页 > 解决方案 > 使用 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);

参考:使用 AES 加密任何文件

有没有办法读取 CryptoStream 的字节数组,然后将其转换为 Base64,因为我看不到bytearrayinput单独存储正确的信息。帮助将不胜感激。谢谢!

标签: c#encryptionaesrijndael

解决方案


第一:密钥是如何创建的?你有没有仔细检查过你的盐是一样的?

我也没有检查过,但是这段代码应该可以工作:

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);

推荐阅读