我正在尝试将以下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)是我应该使用的算法。
有人可以帮我解决问题吗?
答案 0 :(得分:0)
只需改变 -
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;
}