I have been having a problem with doing padded encryption. I think I have isolated the issue to this function:
static String AESEncryptStringWithPassword(String s, String p) throws...{
//function to create key from string password
SecretKey secret = deriveAESKey(p);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(s.getBytes(Charset.forName("UTF-8")));
String str = Base64.getEncoder().encodeToString(ciphertext);
return str;
}
Down the line when I go to decrypt I will get an error like so: Input length must be multiple of 16 when decrypting with padded cipher.
I have checked and this method is the origin of the bad length string. No further methods corrupt it. I'm not sure exactly what I'm doing wrong. I have based my code on the question here: Java 256-bit AES Password-Based Encryption
EDIT: I have changed the encoding slightly to use String(byte[], charset) instead. However now with defaultcharset I have an appropriate string length and with utf-8 I do not.