1

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 ??

1

1 Answer 1

1

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.

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

1 Comment

Java crypto when you specify only an algorithm like 'BLOWFISH' (instead of a 'transform' = algorithm/mode/padding) actually uses ECB and PKCS5-style padding, whereas nodejs crypto uses OpenSSL which defaults if necessary to CBC (and PKCS5). ECB has no IV and also is insecure for nearly all purposes (see numerous Qs about this on security.SX and crypto.SX); CBC does require unique and unpredictable IV.

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.