我遇到了
的问题javax.crypto.Cipher
当我写这行代码时
Cipher cipher;
byte[] bytes = null;
try
{
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, generateAESKey128b(key));
bytes = cipher.doFinal(input.getBytes("UTF-8"));
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
控制台给我这个错误
javax.crypto.IllegalBlockSizeException
Input length must be multiple of 16 when
decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at it.unitn.se.gym.backend.utils.Security.AES128Decode(Security.java:109)
at it.unitn.se.gym.backend.utils.Security.decode_AES128_Base64(Security.java:96)
at it.unitn.se.gym.backend.WebService.main(WebService.java:42)
Exception in thread "main" java.lang.NullPointerException
at it.unitn.se.gym.backend.utils.Security.decode_AES128_Base64(Security.java:97)
at it.unitn.se.gym.backend.WebService.main(WebService.java:42)
前两行代码是正确的但是当我将类型为byte []的属性“text”传递给doFinal函数时,它会给我错误。
有人可以告诉我为什么吗?
解决:
好的,问题解决了
byte[] encrypted = UniversalBase64Encoder.decode(input);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, generateAESKey128b(key));
byte[] originalBytes = cipher.doFinal(encrypted);
这是我写的正确代码
答案 0 :(得分:1)
问题在于您正在尝试解密未加密的字符串,并且这样做违反了解密算法的假设(其输入大小始终是16的倍数)。
这是一段加密然后解密字符串的代码块。请注意,当打印加密的字符串时,它的长度为16个字节,即使输入字符串不是。加密算法在输入字符串加密之前填充输入字符串以使其成为16字节的倍数。这个16字节长的加密字符串现在是解密的有效输入。
这个假设(加密的结果将是偶数大小)是非常标准的。它不仅使解密/加密算法更容易编写,而且还可以防止攻击者知道您加密的事物的长度。
byte[] keyBytes = new byte[16];
keyBytes[0] = 1;
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
String input = "hello";
Cipher cipher;
byte[] bytes = null;
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
bytes = cipher.doFinal(input.getBytes("UTF-8"));
System.out.println("Encoded: "+Arrays.toString(bytes));
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decoded = cipher.doFinal(bytes);
System.out.println("Decoded: "+new String(decoded, "UTF-8"));