javax.crypto.Cipher equivalent code in Nodejs Crypto Javascript

烈酒焚心 提交于 2019-12-06 13:01:00

问题


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

public static String encrypt(String accessToken) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        String merchantKey = "11111111111111111111";
        String st = StringUtils.substring(merchantKey, 0, 16);
        System.out.println(st);
        Key secretKey = new SecretKeySpec(st.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedByte = cipher.doFinal(accessToken.getBytes());

        // convert the byte to hex format
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < encryptedByte.length; i++) {
            sb.append(Integer.toString((encryptedByte[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

Here is what I was able to figure out-

function freeChargeEncryptAES(token){
    var fcKey = "11111111111111111111".substring(0, 16);
    var cipher = crypto.createCipher('aes-128-ecb', fcKey, "");
    var encrypted = cipher.update(token,'ascii','hex');
    encrypted += cipher.final('hex');
    return encrypted;
}

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

token = "abcdefgh"

Java Code output - bc02de7c1270a352a98faa686f155df3

Nodejs Code output - eae7ec6943953aca94594641523c3c6d

I've read from this answer that by default encryption algorithm is aes-ecb which does not need IV. As the key length is 16, I'm assuming aes-128-ecb (16*8 = 128) is the algorithm that I should use.

Can someone help me figure out the problem ??


回答1:


Just need to change -

crypto.createCipher('aes-128-ecb', fcKey, "");

to

crypto.createCipheriv('aes-128-ecb', fcKey, "");

Reason is simple - createCipher method treats second parameter as Encryption Password while it is an Encryption Key.

My bad, even after reading this answer, I've used wrong method (crypto.createCipher instead of crypto.createCipheriv). Below is proper working code in nodejs. That was all needed.

function freeChargeEncryptAES(token){
    var fcKey = "11111111111111111111".substring(0, 16);
    var cipher = crypto.createCipheriv('aes-128-ecb', fcKey, "");
    var encrypted = cipher.update(token,'ascii','hex');
    encrypted += cipher.final('hex');
    return encrypted;
}


来源:https://stackoverflow.com/questions/38352275/javax-crypto-cipher-equivalent-code-in-nodejs-crypto-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!