1

I'm creating a react-native application, where I need to encrypt with TripleDES using ECB mode and Pkcs7 padding. I have an Android Java piece of code that do the encrypt algorithm i want to replicate.

In react-native I added "CryptoJS" from https://github.com/brix/crypto-js and I called CryptoJS.enc.TripleDES.encrypt() method but it returns a different result than expected.

This is Android code i want to reach:

private static byte[] encrypt(String message, String privateKeyMobile) throws Exception {
  final MessageDigest md = MessageDigest.getInstance("MD5");
  final byte[] digestOfPassword = md.digest(privateKeyMobile.getBytes("utf-8"));

  final byte[] keyBytes = new byte[24];
  int q;
  for (q = 0; q < 24 && q < digestOfPassword.length; q++) {
    keyBytes[q] = digestOfPassword[q];
  }
  if (q < 24) {
    for (int u = q; u < 24; u++)
      keyBytes[u] = 0;
  }
  for (int j = 0, k = 16; j < 8;) {
    keyBytes[k++] = keyBytes[j++];
  }

  final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
  final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS7Padding");
  cipher.init(Cipher.ENCRYPT_MODE, key);

  final byte[] plainTextBytes = message.getBytes("utf-8");
  return cipher.doFinal(plainTextBytes);
}

This one is my react-native code:

encrypt(message, key) {
  let md5key = CryptoJS.enc.MD5(key);
  var ciphertext = TripleDES.encrypt(message, md5key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return ciphertext;
}

The two functions returns different outputs.

This php code makes same work as Java code: https://webtools.workontech.com/triple-des-encryption-online

Other online TripleDES tools return the same react-native result.

Faisal Rahman Avash
  • 1,268
  • 9
  • 13
  • if you are only attracted on android side of this you have https://facebook.github.io/react-native/docs/native-modules-android as a viable option. This will save you time and compatibility – DNA.h Jun 27 '19 at 08:00
  • Sadly I need to support iOS too – Alberto Barbieri Jun 27 '19 at 08:14
  • then I'm afraid you either have to implement encrypt yourself, or trust crypto-js library. btw crypto-js is a powerful and well-tested library, most probably you are safe to use both encrypt and decrypt from crypto-js. You can run js functions in php too if online tools are not suffiecent – DNA.h Jun 27 '19 at 08:47

0 Answers0