javax.crypto.Cipher Nodejs Crypto 中的等效代码 Javascript

javax.crypto.Cipher equivalent code in Nodejs Crypto Javascript

我正在尝试将以下 java 代码转换为 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();
    }

这是我能够弄清楚的-

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;
}

我无法获得相同的输出。例如,如果

token = "abcdefgh"

Java 代码输出 - bc02de7c1270a352a98faa686f155df3

Nodejs 代码输出 - eae7ec6943953aca94594641523c3c6d

我从 this answer 那里了解到,默认加密算法是 aes-ecb,不需要 IV。由于密钥长度为 16,我假设 aes-128-ecb (16*8 = 128) 是我应该使用的算法。

谁能帮我解决这个问题??

只需要改变-

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

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

原因很简单 - createCipher 方法将第二个参数视为 Encryption Password 而它是 Encryption Key.

我的错,即使在阅读 this answer 之后,我还是使用了错误的方法(crypto.createCipher 而不是 crypto.createCipheriv)。下面是 nodejs 中正确的工作代码。这就是所有需要的。

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;
}