【问题标题】:"Specified cipher mode is not valid for this algorithm" in .NET CORE but working in .NET Standard.NET CORE 中的“指定密码模式对此算法无效”,但在 .NET Standard 中工作
【发布时间】:2021-08-02 19:15:43
【问题描述】:

我正在尝试解密 aes 加密文件。我能够成功解密 .NET Standard 中的文件。但是当我在 .NET Core 中使用相同的代码时,我得到了以下异常。

System.Security.Cryptography.CryptographicException: 'Specified cipher mode is not valid for this algorithm.'

这是我用来解密的代码。

public void FileDecrypt(string inputFile, string outputFile, string password)
    {
        byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
        byte[] salt = new byte[32];

        FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
        fsCrypt.Read(salt, 0, salt.Length);

        RijndaelManaged AES = new RijndaelManaged();
        AES.KeySize = 256;
        AES.BlockSize = 128;
        var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
        AES.Key = key.GetBytes(AES.KeySize / 8);
        AES.IV = key.GetBytes(AES.BlockSize / 8);
        AES.Padding = PaddingMode.PKCS7;
        AES.Mode = CipherMode.CFB;

        using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read))
        {
            using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
            {
                int read;
                byte[] buffer = new byte[1048576];

                while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fsOut.Write(buffer, 0, read);
                }
            }
        }
    }

如果我在 .NET Core 中删除密码模式并解密,我会收到填充无效异常。

System.Security.Cryptography.CryptographicException: 'Padding is invalid and cannot be removed.'

我更改了不同的填充模式并尝试了,但输出文件无效(未正确解密)。

为什么我在 .Net Core 而不是在 .Net Standard 中出现 Cipher Mode Invalid 异常? 我应该在 .NET Core 中进行哪些更改才能正确解密?

我正在使用

.NET Core SDK (reflecting any global.json):
Version:   2.1.503

【问题讨论】:

  • 貌似目前没有在.NET Core中实现,但应该在.NET Core 3中实现。Issues 4647

标签: c# encryption .net-core aes .net-standard


【解决方案1】:

【讨论】:

    【解决方案2】:

    在 .NET 5.0 中通过dotnet/runtime PR #38211(重新)引入了 CFB 支持。

    在 .NET 5.0 之前,模式确实仅限于 CBC = 1、ECB = 2 和 CTS = 5。现在还支持 CFB = 4: https://github.com/dotnet/runtime/blob/main/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CipherMode.cs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多