简体   繁体   中英

How can I convert this java code to javascript

My code should get an encrypted plaintext from the server and decrypts it in react-native with javascript. I have decryption function in java but how can I convert it to javascript?

I tried cryptojs with no success. Because the cipher IV made but a byte array and javascript hasn't the byte data type

public static String decrypt(String plainText, String key) throws Exception {
    byte[] clean = new BASE64Decoder().decodeBuffer(plainText);

    int keySize = 16;
    byte[] keyBytes = new byte[keySize];

    byte[] pwbyte = key.getBytes("UTF-8");

    int len = pwbyte.length;

    if (len > keyBytes.length) {
        len = keyBytes.length;
    }

    System.arraycopy(pwbyte, 0, keyBytes, 0, len);
    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

    IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
    byte[] encrypted = cipher.doFinal(clean);

    return new String(encrypted, "UTF-8");
}

I faced the issue of data type mismatch for byte array when rewriting a Python driver to Node.js. In my case I had used the tweetnacl which is a port of the NACL library in JS. I solved the problem here .

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM