I'm trying to replicate the encryption used in a Java application using Javascript and CryptoJS. I'm not quite sure how I should be replicating the SecretKeySpec, as it seems CryptoJS expects a string for the key.
Here is the Java encryption code that I need to replicate in JS:
public byte[] encrypt(byte[] origin) { String key = "testkey"; SecretKeySpec sks = new SecretKeySpec(convertAESKey(key), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] iv = new byte[16]; cipher.init(Cipher.ENCRYPT_MODE, sks, new IvParameterSpec(iv)); return cipher.doFinal(origin); } private byte[] convertAESKey(String key) { byte[] keyBytes; keyBytes = key.getBytes("UTF-8"); byte[] keyBytes16 = new byte[16]; System.arraycopy(keyBytes, 0, keyBytes16, 0, Math.min(keyBytes.length, 16)); return keyBytes16; } } My JS code so far:
var iv = new Uint8Array(16); var key = "testkey"; var encrypted = CryptoJS.AES.encrypt( someByteArray, key, { iv: iv, mode: CryptoJS.mode.CBC } ); Also, the final output of cipher is a encrypted byte array. The final output of CryptoJS appears to be an object with cipherText. Is there a way to get the output as a byte array ?
The only thing I could think of now is to convert the encrypted response into a string, then converting that into a byte array, but this doesn't seem to match the output of the Java encryption.