How To Implement This Encryption?

mituso

New Member
17/9/19
2
0
1
30
I have never used java. so i have a question please help me.

I have following code in Java.
Code:
String secretString = 'hf4*lP@hna'
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom securerandom = SecureRandom.getInstance("SHA1PRNG");
securerandom.setSeed(secretString.getBytes());
kgen.init(128, securerandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] byteContent = content.getBytes("utf-8");
byte[] cryptograph = cipher.doFinal(byteContent);
String enc1 = Base64.getEncoder().encodeToString(cryptograph);
return enc1;
I need to implement it in JavaScript/Node.js, however I can only figure out the last half in js like below
Code:
const crypto = require('crypto');
const ALGORITHM = 'AES-128-cbc';
const secretString = 'hf4*lP@hna'
// missing part in JS (how to convert secretString to key)
function encrypt(plaintext, key) {
   const cipher = crypto.createCipheriv(ALGORITHM, key, Buffer.alloc(0));
   return cipher.update(plaintext, 'utf8', 'base64') + cipher.final('base64');
}
I don't uderstand how the KeyGenerator and SecureRandom works and How to convert it to code nodejs/javascript
 
Last edited by a moderator:

Joe

Thành viên VIP
21/1/13
2,686
1,243
113
Java and JavaScript are two different shoes. NodeJS is another thing. If you want to invoke a JAVA method from JavaScript you have to develop a bridge like JNI (Java Native Interface) for C/C++. If you're a newbie or a beginner who cannot develop a bridge you could use THIS BRIDE.
 

mituso

New Member
17/9/19
2
0
1
30
Thank Joe. I have to connect with a supplier and They give me java code to encode param however my system is using nodejs for backend, so I need convert javacode to nodejs
 

Joe

Thành viên VIP
21/1/13
2,686
1,243
113
Thank Joe. I have to connect with a supplier and They give me java code to encode param however my system is using nodejs for backend, so I need convert javacode to nodejs
Well, the problem is that JAVA and JavaScript are 2 different languages -even they share the prefix JAVA. To "convert" JAVA to JavaScript or vice versa you need a technique called TRANSPILER -a combination between TRANSlator and comPILER. It's a bite complicated because it requires you the knowledge of both languages. However, you could try with JSWEET.
 

badboy3283

Active Member
20/10/11
295
89
28
District BT, HCM City
Check this lib: https://jwt.io/. It supports encode and decode for almost language.

By the way, the reason that the code can't combine with Nodejs is here:
Code:
SecureRandom securerandom = SecureRandom.getInstance("SHA1PRNG");
securerandom.setSeed(secretString.getBytes());