I need to encrypt and decrypt data from both Java (on Android) and SJCL (I could plausibly switch to another JS cryptographic library, but I am familiar with SJCL, so I would prefer to stick with it if possible).
I have the end of SJCL, but at the end of Java Iām not quite sure which parameters I need to use to configure the key generator and encryption. The code I still used to decrypt:
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1024, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8"); return plaintext;
When salt, iv and ciphertext are extracted as strings from a JSON object created by SJCL, and then decoded using Base64 decoder into byte arrays.
Unfortunately, I have a few problems with this, and the code above does not work.
The first problem is that PBKDF2WithHmacSHA256 does not seem to be a recognized key generation algorithm. I'm not quite sure if this is what I want, but it seems to be correct based on reading the SJCL documentation? Java recognizes PBKDF2WithHmacSHA1, but this is not like the same algorithm that implements SJCL.
Secondly, if I try to use the SHA1 key algorithm, I get an error message with an invalid key size. Do I need to install something to enable AES with 256-bit keys? Calling a factory key to create a 128-bit key works fine (although, obviously, it is not compatible with SJCL, which uses a 256-bit key).
Third, what encryption mode should I use? I'm sure CBC is wrong ... The SJCL documentation mentions both CCM and OCB, but Java doesn't seem to support any of them out of the box - again, do I need to install something to make this work? And which one uses SJCL by default?
And finally, even if I choose the parameters that cause Java not to complain about the missing algorithms, he complains that the IV provided by decoding the SJCL output is of the wrong length, which certainly looks like this: the result is a 17 byte output, not 16, as AES seems to require. Am I just ignoring the last byte?