【发布时间】:2018-06-23 22:18:40
【问题描述】:
我花了一整天的时间对此进行调查,并在 Stack Overflow 上搜索所有相关问题以查找此问题,因此请不要提及可能的重复项。
下面的代码给了我一个 System.Security.Cryptography.CryptographicException: 'Specified padding mode is not valid for this algorithm。'
虽然在本网站上使用相同的参数:http://aes.online-domain-tools.com,但它完美地解密为“Hello world”,然后填充五个“x05”字节用于填充(PKCS#7 填充)。
但是下面的代码在调用TransformFinalBlock()时总是会产生异常
上下文: 使用 .NET Core 2.0 在 Win8.1 上运行的控制台应用程序 / 算法是 AES / CBC / padding PKCS#7
我也在这里尝试了建议的解决方案:Specified padding mode is not valid for this algorithm - c# - System.Security.Cryptography 但没有成功(我也不明白为什么如果已经在 SymmetricAlgorithm 实例中设置了 IV,则应该稍后在解密时使用它?
static void Main(string[] args)
{
string encryptedStr = "e469acd421dd71ade4937736c06fdc9d";
string passphraseStr = "1e089e3c5323ad80a90767bdd5907297b4138163f027097fd3bdbeab528d2d68";
string ivStr = "07dfd3f0b90e25e83fd05ba338d0be68";
// Convert hex strings to their ASCII representation
ivStr = HexStringToString(ivStr);
passphraseStr = HexStringToString(passphraseStr);
encryptedStr = HexStringToString(encryptedStr);
// Convert our ASCII strings to byte arrays
byte[] encryptedBytes = Encoding.ASCII.GetBytes(encryptedStr);
byte[] key = Encoding.ASCII.GetBytes(passphraseStr);
byte[] iv = Encoding.ASCII.GetBytes(ivStr);
// Configure our AES decryptor
SymmetricAlgorithm algorithm = Aes.Create();
algorithm.Mode = CipherMode.CBC;
algorithm.Padding = PaddingMode.PKCS7;
algorithm.KeySize = 256;
//algorithm.BlockSize = 128;
algorithm.Key = key;
algorithm.IV = iv;
Console.WriteLine("IV length " + iv.Length); // 16
Console.WriteLine("Key length " + key.Length); // 32
ICryptoTransform transform = algorithm.CreateDecryptor(algorithm.Key, algorithm.IV);
// Perform decryption
byte[] outputBuffer = transform.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
// Convert it back to a string
string result = Encoding.ASCII.GetString(outputBuffer);
Console.WriteLine(result);
Console.ReadLine();
}
public static string HexStringToString(string hexString)
{
var sb = new StringBuilder();
for (var i = 0; i < hexString.Length; i += 2)
{
var hexChar = hexString.Substring(i, 2);
sb.Append((char)Convert.ToByte(hexChar, 16));
}
return sb.ToString();
}
【问题讨论】:
标签: c# .net encryption .net-core aes