繁体   English   中英

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

[英]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

我从这个答案中读到,默认加密算法是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

我的坏,即使在阅读了这个答案后 ,我也使用了错误的方法(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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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