I am having problems with keys AES
in Java
This is my code:
public Core(String key) {
try {
this.SecretKey = key;
this.ivspec = new IvParameterSpec(this.iv.getBytes());
this.keyspec = new SecretKeySpec(SecretKey.getBytes("UTF-8"), "AES");
try {
this.cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (Exception e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Whenever I pass the String "key" that contains for example Pizza
, it just generates errors. When I pass for example a String that contains precisely 16 bytes, it works. I would like to use AES, but I would not like it to only be limited to 16, 24 or 32 bytes. How can I fix this?
For AES with different key sizes (and different block sizes) look at Rijndael. However, given your use of "Pizza" as a key, using Rijndael is probably too advanced for you. Instead use a Key Derivation Function (KDF) to turn your password ("Pizza") into a cryptographic key. Have a look at PBKDF2
if you are not sure what KDF to use.
I would also recommend using a passphrase instead of a password as input to your KDF: "I like Ham and Pineapple Pizza."
ETA: Prefer PKCS7
padding to NoPadding. That way you will catch more errors in your code when the padding does not match.