【发布时间】:2018-07-17 20:17:01
【问题描述】:
我面临 AES 填充问题。 我正在使用 Alcides Soares FIlho 在 (generate a 128-bit string in C#) 中建议的代码。 请注意,我的加密侧代码是...
private string Encrypt(string clearText)
{
string EncryptionKey = "I love chocolate";
byte[] clearBytes =
System.Text.Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new
Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e,
0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms,
encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
另外,我传递给明文的值是“Z4YAZZSQ 001F295E2589AWAN HANS”。加密正在发生。但解密失败。
解密端代码
private string Decrypt(string cipherText)
{
string EncryptionKey = "I love chocolate";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65,
0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms,
encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText =
System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
我应该可以找回“Z4YAZZSQ 001F295E2589AWAN HANS”
但出现以下错误“填充无效且无法删除” 请提出解决方案。
【问题讨论】:
-
您很可能没有面临 AES 填充问题,而是由于不正确的参数、编码和/或数据而导致解密失败。如果解密失败,则填充也无效。验证填充解密指定没有填充,然后检查最后 16 个字节(十六进制)。调试,验证输入是否正确,编码是否正确等。通过使用静态密钥和 VI 来简化调试消除密钥派生等。删除尽可能多的代码以获得加密/解密的 mimcl 版本在职的。然后一次一个地添加碎片。
-
您的代码工作正常(忽略各种安全问题,例如硬编码密钥、从密钥派生的 IV 等)。因此,您必须在加密和解密之间对密文进行破坏。
-
谢谢大家的建议。显然在 cs.write() 解决问题之后使用 cs.FlushFinalBlock() 。我还是不知道怎么办。但它奏效了。另外,@Iridium:正如您所指出的存在一些安全问题,您能否为一般行业实践提供一些指导。
标签: encryption key aes badpaddingexception