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.