简体   繁体   中英

(Java to Javascript) javax.crypto.Cipher equivalent code in Nodejs Crypto Javascript

I'm trying to convert below java code into nodejs.


    private static String TRANS_MODE = "Blowfish";

    private static String BLOWFISH_KEY = "BLOWFISH_KEY";

    public static String encrypt(String password) throws Exception {

    SecretKeySpec keySpec = new SecretKeySpec(BLOWFISH_KEY.getBytes("Windows-31J"),TRANS_MODE);
    Cipher cipher;
    cipher = Cipher.getInstance(TRANS_MODE);

    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    byte[] passByte;
    passByte = cipher.doFinal(password.getBytes("Windows-31J"));


    return new String(Hex.encodeHex(passByte));

    }

Here is what I was able to figure out-



const crypto = require('crypto');

function encrypt(password)  
  var fcKey = "BLOWFISH_KEY";
  var cipher = crypto.createCipher('BF-CBC', fcKey, "");
  var encrypted = cipher.update(password,'ascii','hex');
  encrypted += cipher.final('hex');
return encrypted;

I'm not able to get same output. For example if

password= "password01"

Java Code output - fe0facbf8d458adaa47c5fe430cbc0ad

Nodejs Code output - ae5e8238c929b5716566e97fa35efb9b

Can someone help me figure out the problem??

Notice that crypto.createCipher(algorithm, password[, options]) is deprecated and should not be used.

Where the SecretKeySpec(..) in java takes a binary key as input, the createCipher(..) in js takes a "password" as input, and behind the scene tries to derive a binary key using MD5. So your actually key used in the two programs ends up being different. The js methode also tries to derive an IV from the password, which is bad practice and different from your java code.

In js you need to use the crypto.createCipheriv() instead. And when you are at it, you also need to consider if an iv is needed - both in Java and in js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM