首页 > 解决方案 > Java 到 Node.js AES/ECB/PKCS5Padding 加密

问题描述

我在 JAVA 中有以下加密功能。我正在尝试使用来自加密的密码在 Node.js 中编写相同的加密。但是,输出不一样。它使用相同的键和输入。

JAVA

public static String encrypt(String input, String key) {
    byte[] crypted = null;
    try {
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        crypted = cipher.doFinal(input.getBytes());
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    String result = new String(Base64.encodeBase64(crypted));
    return result.replace("+", "-");
}

示例输出:0HCkcjWj/PoCZ4ZUFJARs/m4kstigMFk8dQnT0uNhog=(44 个字符)

节点.js

encrypt = (input, key) => { 
    const algorithm = 'aes-128-cbc';   
    key = crypto.scryptSync(key, 'salt', 16);       
    const iv = Buffer.alloc(16, 0);
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    cipher.setAutoPadding(true);
    let encrypted = cipher.update(input, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    return encrypted.replace('+','-');
}

示例输出:ZHtEbAhrIo7vWOjdMNgW6Q==(24 个字符)

提前致谢。

标签: node.jsencryptionaes

解决方案


以便 NodeJS 代码在功能上与 Java 代码相同,在 NodeJS 代码中:

  • 必须使用 ECB 模式而不是 CBC 模式:

    const algorithm = 'aes-128-ecb';
    ...
    //const iv = Buffer.alloc(16, 0); // remove
    const cipher = crypto.createCipheriv(algorithm, key, null);
    

    但是请注意,ECB 不使用 IV,通常是不安全的,因此不应使用,[1]。更好的选择是 CBC 模式(机密性)或 GCM 模式(机密性、真实性/完整性)、[2][3]

  • 不得应用密钥派生函数[4],即必须删除以下行:

    key = crypto.scryptSync(key, 'salt', 16); 
    

推荐阅读