As I try to convert a hex string
to a byte array
I get this exception :
Aug 15, 2013 10:17:32 PM Tester main
SEVERE: null
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(BlowfishCipher.java:319)
at javax.crypto.Cipher.doFinal(Cipher.java:1978)
at Tester.main(Tester.java:21)
Following is the code that attempted so :
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
SecretKey secretKey = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
String decryptSt = new String(cipher.doFinal(DatatypeConverter.parseHexBinary("f250d7a040859d66541e2ab4a83eb2225d4fff880f7d2506")));
System.out.println(decryptSt);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
}
What is the problem ? Why am I getting an exception ?
You can never decrypt with a random key. If you do, you will get plaintext consisting of random bytes. The cipher however tries to unpad the message. As it does not find a valid padding, you will get this exception. Note that - by "luck", about once in 256 - the padding may be correct, in which case you simply retrieve random bytes as plaintext.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.