node.js - 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 个字符)
提前致谢。
解决方案
以便 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);
推荐阅读
- git - 我可以在不更改 URL 的情况下重命名 Git 子目录(为其内容)吗?
- sql - Postgresql:如何加入未在 from 子句中引用的表?
- vue.js - 包装器组件中的 vuejs beforeDestory 钩子
- javascript - 水平滚动不适用于 fullpage.js
- python - 如何将传入的烧瓶请求重定向到多个端点?
- spring - Kubernetes集群上的Spring“无法在...下绑定属性”
- android - Android Studio 模拟器不显示颤振应用程序
- angular - 覆盖滚动条样式的角度虚拟滚动性能问题
- flutter - 颤振:参数格式不正确
- javascript - 函数调用之间的时间间隔