通过使用 AES 算法进行字符串解密,我遇到了非常奇怪的问题。我的 C# 应用程序将加密数据(字符串)发送到 Java 应用程序。即使我使用相同的密钥字符串,解密也会导致异常:
javax.crypto.BadPaddingException:给定最终块在 com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:810) 处未正确填充
但是,仅当要加密的纯输入文本的长度(在 C# 端)超过 1393 个字符时...但如果长度等于 1393 个字符,或者小于 1393 个字符,则可以正常工作。
这是用于加密的 C# 代码:
private static string Encrypt(string textToEncrypt, string key)
{
try
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 0x80; // 256bit key
rijndaelCipher.BlockSize = 0x80;
byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[0x10];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
}
catch (Exception ex)
{
throw ex;
}
}
以及用于解密的 Java 代码:
public static String Decrypt(String text, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes = new byte[16];
byte[] b = key.getBytes("UTF-8");
int len = b.length;
if (len > keyBytes.length) {
len = keyBytes.length;
}
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
BASE64Decoder decoder = new BASE64Decoder();
byte[] results = cipher.doFinal(decoder.decodeBuffer(text));
return new String(results, "UTF-8");
}
我尝试将 BASE64Decoder 从 apache 替换为 Base64 编解码器,但结果是一样的……我将不胜感激任何建议或想法。谢谢。