[SOLVED] Help converting JavaScript to Java

Hi guys

Could someone give me a hand with this as I’m struggling.

Javascript code:

const key = this.crypto.createHash('md5').update(Buffer.from(deviceInfo.apiKey, 'utf8')).digest()
const dText = this.crypto.createDecipheriv('aes-128-cbc', key, Buffer.from(rdata.iv, 'base64'))
const pText = Buffer.concat([dText.update(Buffer.from(data, 'base64')), dText.final()]).toString('utf8')

My attempt that doesn’t work:

// 1
MessageDigest hash_ = MessageDigest.getInstance("MD5");
hash_.update(deviceKeyBytes);
byte[] keyBytes = hash_.digest();
SecretKeySpec key = new SecretKeySpec(keyBytes, "RawBytes");
// 2
String encrypted = data1 + data2;
IvParameterSpec iv = new IvParameterSpec(ivBase64);
Cipher dText = Cipher.getInstance("AES/CBC/PKCS5PADDING");
dText.init(Cipher.DECRYPT_MODE, key, iv);
// 3
byte[] pText = dText.doFinal(Base64.getDecoder().decode(encrypted));
String json = new String(pText, StandardCharsets.UTF_8);

Managed to figure it out myself after a lot of trial and error.

public String decrypt(JsonObject payload, String deviceKey) {

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytesOfMessage = deviceKey.getBytes("UTF-8");
            byte[] keyBytes = md.digest(bytesOfMessage);
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            String encoded = payload.get("data1").getAsString() + payload.get("data2").getAsString();
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] ciphertext = Base64.getDecoder().decode(encoded);
            String ivString = payload.get("iv").getAsString();
            byte[] ivBytes = Base64.getDecoder().decode(ivString);
            IvParameterSpec iv = new IvParameterSpec(ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            byte[] padded = cipher.doFinal(ciphertext);
            String unpadded = new String(padded, StandardCharsets.UTF_8);
            return unpadded;

        } catch (Exception e) {
            logger.debug("Exception: {}", e);
            return null;
        }
    }