Toggle Theme Editor
Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate Charcoal

How To Implement This Encryption?

Discussion in 'Xây dựng các ứng dụng Java khác, các vấn đề khác' started by mituso, 17/9/19.

  1. mituso

    mituso New Member

    I have never used java. so i have a question please help me.

    I have following code in Java.
    String secretString = 'hf4*lP@hna'
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom securerandom = SecureRandom.getInstance("SHA1PRNG");
    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
    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') +'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: 17/9/19
  2. Joe

    Joe Thành viên VIP

    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.
  3. mituso

    mituso New Member

    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
  4. Joe

    Joe Thành viên VIP

    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.
  5. badboy3283

    badboy3283 Active Member

    Check this lib: It supports encode and decode for almost language.

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

Chia sẻ trang này