【发布时间】: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