Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  0] [ 2]  / answers: 1 / hits: 13779  / 4 Years ago, tue, february 18, 2020, 12:00:00

I am trying to replicate the Java code for AES Encryption and Decryption in Node JS.



Java Code



    SecretKeySpec skeySpec;
String key = a4e1112f45e84f785358bb86ba750f48;

public void encryptString(String key) throws Exception {
try {
skeySpec = new SecretKeySpec(key.getBytes(), AES);
cipher = Cipher.getInstance(AES);
cipher.init(1, skeySpec);
byte encstr[] = cipher.doFinal(message.getBytes());
String encData = new String(encstr, UTF-8);
System.out.println(encData);
} catch (NoSuchAlgorithmException nsae) {
throw new Exception(Invalid Java Version);
} catch (NoSuchPaddingException nse) {
throw new Exception(Invalid Key);
}
}


Node JS



    var encryptKey = function (text) {
var cipher = crypto.createCipher('aes256', 'a4e1112f45e84f785358bb86ba750f48');
var crypted = cipher.update(text,'utf8', 'hex')
crypted += cipher.final('hex');
console.log(crypted);
return crypted;
}


I am unable to get the exact cipher-text in Node JS, which i am getting in Java.


More From » java

 Answers
1

Finally after reviewing Java Docs and Node JS Crypto Docs managed to get the result.
We have to use crypto.createCipheriv() instead of crypto.createCipher with a iv.
Here iv will be null.



Code :



    let crypto = require('crypto');

var iv = new Buffer.from(''); //(null) iv
var algorithm = 'aes-256-ecb';
var password = 'a4e1112f45e84f785358bb86ba750f48'; //key password for cryptography

function encrypt(buffer){
var cipher = crypto.createCipheriv(algorithm,new Buffer(password),iv)
var crypted = Buffer.concat([cipher.update(buffer),cipher.final()]);
return crypted;
}

console.log(encrypt(new Buffer('TextToEncrypt')).toString())

[#4714] Friday, February 14, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janettejordynm

Total Points: 550
Total Questions: 94
Total Answers: 98

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
janettejordynm questions
Tue, Nov 24, 20, 00:00, 4 Years ago
Sat, May 23, 20, 00:00, 4 Years ago
Mon, Apr 6, 20, 00:00, 4 Years ago
Wed, Oct 23, 19, 00:00, 5 Years ago
;