0

I want to duplicate the JAVA encryption code in NodeJS.

private String DEFAULT_KEY = "abcdwAYserXbzcSeqL/zPg==";
private String text = "abc";
Base64 base64decoder = new Base64();
byte[] raw = base64decoder.decode(key);

SecretKeySpec fSecretKeySpec = new SecretKeySpec(raw, "AES");

Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, fSecretKeySpec);
byte[] encrypted = cipher.doFinal(text.getBytes());

Base64 base64encoder = new Base64();
result = base64encoder.encodeToString(encrypted);
System.out.println("result: "+ result);

The above code generate the encrypted code as: ZkojvMTW+9EEK0owxMuA7A==

I have tried few ways in NodeJS. It is not generating same code for me.

I have tried the following code.

var bKey = new Buffer('abcdwAYserXbzcSeqL/zPg==', 'base64');
var cipher = crypto.createCipher('aes-128-ecb',bKey);
//cipher.setAutoPadding(auto_padding=false);
var crypted = cipher.update('abc',null,'base64');
crypted+=cipher.final('base64');
console.log(crypted);

Can someone help me out?

7
  • What have you tried? Stackoverflow is a community that will help but you most show some code or things you have tried. Commented Jul 22, 2015 at 12:44
  • @JeffSloyer - This is the one way I have tried. var bKey = new Buffer('abcdwAYserXbzcSeqL/zPg==', 'base64'); var cipher = crypto.createCipher('aes-128-ecb',bKey); var encrypted = cipher.update('xls', 'base64', 'base64') + cipher.final('base64') Commented Jul 22, 2015 at 14:48
  • I added your code to your question. Commented Jul 22, 2015 at 14:50
  • What version of AES are you doing? Commented Jul 22, 2015 at 14:54
  • @JeffSloyer Thanks. I have tried with AES 128 bit used in java. So I used 'aes-128-ecb' first in nodejs code.Then I have tried with all available ciphers in the NodeJS through the following code 'var chipers = crypto.getCiphers(); for (var i = 0; i < chipers.length; i++) { //Encryption method }' None of the ciphers gave the same result as JAVA. Please help me to identify the issue in NodeJS code. Commented Jul 22, 2015 at 15:02

1 Answer 1

1

You probably are running into the issue that createCipher with two arguments takes a password, not a key. This password is first run through a key derivation function before it becomes a key.

Try to use the createCipheriv method instead, using any value for the IV. ECB mode doesn't take an IV, but at least you would be using a key instead of a password.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.