TLDR; In Java using AES cryptography, how do I pack encrypted messages together to decrypt with a single decryption call?
I am using AES cryptography in an android chat application, and when decrypting multiple messages (using the same key), the program becomes very slow to the the point where I have to use multithreading so it does not freeze the system.
I understand there is a way to pack encrypted messages together to decrypt them all at once which should be much faster, but I cannot find anything online about how to do this in Java/Kotlin. The only way I can think to do this is append the plaintext together with delimiters and encrypt it, but I would need to change my database to store a single record that contains a large text field, and my professor explicitly stated that changes cannot be made after week 4, and it is week 6. Is there any other way I can achieve this with a list of already encrypted messages?
Edit - Here is the decryption function that is called for each message:
private String decrypt(String strToDecrypt, String secretKey, String username) {
try {
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), username.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec newSecretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, newSecretKey, ivspec);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " e.toString());
}
return null;
}
CodePudding user response:
Password-based key derivation functions are designed to be expensive (to prevent brute-forcing), yet you are preforming that expensive function on every decrypt.
The key derivation will predominate your run time. The AES portion is likely tiny. Since secretKey
and username
are likely to be the same for multiple messages, you should derive the key once and use the cached key as long as the secret key and username remain the same.