-1

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");
}
Morteza
  • 103
  • 1
  • 8
  • 1
    https://stackoverflow.com/questions/29512858/cryptojs-and-key-iv-length – Elliott Frisch Jan 06 '19 at 06:57
  • You can try the `nacl` library. Check this out: https://tweetnacl.js.org/. Also this might be helpful along the way (if you decide to go with tweetNacl): https://stackoverflow.com/questions/51978889/how-to-generate-a-sha256-hash-of-32-bytes-using-nodejs-crypto-in-order-to-avoi – Abrar Jan 06 '19 at 07:40
  • It seems you are creating an IV while decrypting. You should pass the IV that was used to encrypt to the decrypt method. That doesn't answer your question, but you need that fixed in your Java code. – Darlesson Feb 26 '19 at 19:38

1 Answers1

1

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.

Abrar
  • 6,874
  • 9
  • 28
  • 41