I'm trying to encrypt a string on Android with AES. The symmetric key is determined previously with the Diffie-Hellman algorithm and seems to be ok (Key Length is 128 Bit, see below).
Nevertheless, I get a InvalidKeyException: "Key length not 128/192/256 bits.
"
Code:
KeyAgreement keyAgree = KeyAgreement.getInstance("DH", "BC");
keyAgree.init(this.smartphonePrivKey);
keyAgree.doPhase(serverPubKey, true);
SecretKey key = keyAgree.generateSecret("AES");
System.out.println("Key Length: " + key.getEncoded().length);
System.out.println("Key Algorithm: "+ key.getAlgorithm());
System.out.println("Key Format: "+ key.getFormat());
byte[] encrypted = null;
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
System.out.println("Allowed Key Length: "
+ cipher.getMaxAllowedKeyLength("AES"));
cipher.init(Cipher.ENCRYPT_MODE, key);
encrypted = cipher.doFinal("YEAH".getBytes("UTF8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
The above Code leads to the following output:
_12-10 20:24:53.119: INFO/System.out(757): Key Length: 128_
_12-10 20:24:53.119: INFO/System.out(757): Key Algorithm: AES_
_12-10 20:24:53.119: INFO/System.out(757): Key Format: RAW_
_12-10 20:24:53.470: INFO/System.out(757): Allowed Key Length: 2147483647_
After that, I get the InvalidKeyException: Key length not 128/192/256 bits.
But as you can see, the SecretKey has a length of 128 Bits!
Any ideas?
Advanced Encryption Standard (AES) keys are symmetric keys that can be three different key lengths (128, 192, or 256 bits). AES is the encryption standard that is recognized and recommended by the US government. The 256-bit keys are the longest allowed by AES.
An AES 256-bit key can be expressed as a hexadecimal string with 64 characters.
The key you generated is 128 bytes, not 128 bits. "Key Length" should be 16.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With