Question

I have written a simple Java AES encryption and decryption as below (for learning purpose):

//Encryption 
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
 String encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
return encryptedString;

//Decryption
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
return decryptedString;

The cipher key is a variable-length string, I MD5 hash the string to get the 128 bit key.

I can successfully encrypt and decrpyt the data using the same key. But if I decrypt the data with wrong key, I got the exception below:

javax.crypto.BadPaddingException: Given final block not properly padded

Actually what I expect is, a wrong bytes produced from wrong-key-decryption, but not exception thrown like above, because if wrong bytes are produced, hacker might not know whether the decryption is correct or not. If exception thrown like above, the output of brute force will become easier to determine.

So, what happen to my code?

Edit:

I think I made a mistake here. The hacker might not use my program to decrypt. So for AES, if a person is decrypting fail, he will know the decryption was fail but not as I thought that getting wrong bytes from decryption? This is terrible...

Était-ce utile?

La solution

There is nothing wrong with your code (although you could make it more robust by specifying an encoding for the transformations between characters and bytes rather then to rely on the platform encoding). The padding has a certain format so that it can be removed after decryption. When you decrypt with a wrong key, the padding is garbled as well and cannot be removed. This causes the exception.

In most cases an attacker will know that he has got the wrong key not only because of the padding. The data bytes usually also have some structure (eg. a certain file format) or in your case, he will detect unusual characters or an invalid character encoding. If you take UTF-8 for example, not every binary string is a valid UTF-8 encoding.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top