I have Java encrypted code. I am trying to migrate part of the encryption to node. Basically, node will do the encryption using a crypto module, and then Java will do the decryption.
This is how I do encryption in Java:
protected static String encrypt(String plaintext) { final byte[] KEY = { 0x6d, 0x79, 0x56, 0x65, 0x72, 0x79, 0x54, 0x6f, 0x70, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x4b }; try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); final SecretKeySpec secretKey = new SecretKeySpec(KEY, "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); final String encryptedString = Base64.encodeToString( cipher.doFinal(plaintext.getBytes()), Base64.DEFAULT); return encryptedString; } catch (Exception e) { return null; } }
This is how I do encryption in node:
var crypto = require('crypto'), key = new Buffer('6d7956657279546f705365637265744b', 'hex'), cipher = crypto.createCipher('aes-128-ecb', key), chunks = []; cipher.setAutoPadding(true); chunks.push(cipher.update( new Buffer(JSON.stringify({someKey: "someValue"}), 'utf8'), null, 'base64')); chunks.push(cipher.final('base64')); var encryptedString = chunks.join('');
In Java, I get the line T4RlJo5ENV8h1uvmOHzz1KjyXzBoBuqVLSTHsPppljA= . This is decrypted correctly. However, in node I get al084hEpTK7gOYGQRSGxF+WWKvNYhT4SC7MukrzHieM= , which is clearly different and therefore it will not be decrypted correctly.
I tried looking for people who have the same problems as me, and this github Question is the closest I can find. As suggested in this release, I tried to run openssl as follows:
$ echo -e '{"someKey": "someValue"}' | openssl enc -a -e -aes-128-ecb -K "6d7956657279546f705365637265744b" T4RlJo5ENV8h1uvmOHzz1MY2bhoFRHZ+ClxsV24l2BU=
The result I got was pretty close to the one that java created, but still different:
T4RlJo5ENV8h1uvmOHzz1MY2bhoFRHZ+ClxsV24l2BU= // openssl T4RlJo5ENV8h1uvmOHzz1KjyXzBoBuqVLSTHsPppljA= // java al084hEpTK7gOYGQRSGxF+WWKvNYhT4SC7MukrzHieM= // node
Which brings me to the question of how to make node output the same encrypted string as my java code? I can change my code only in node, but not in java.