Nodejs Crypto Javascript中的javax.crypto.Cipher等效代码 [英] javax.crypto.Cipher equivalent code in Nodejs Crypto Javascript
问题描述
我正在尝试将以下java代码转换为nodejs。
I'm trying to convert below java code into 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();
}
这是我能够弄清楚的 -
Here is what I was able to figure out-
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;
}
我无法获得相同的输出。例如,如果
I'm not able to get same output. For example if
token =abcdefgh
token = "abcdefgh"
Java代码输出 - bc02de7c1270a352a98faa686f155df3
Java Code output - bc02de7c1270a352a98faa686f155df3
Nodejs代码输出 - eae7ec6943953aca94594641523c3c6d
Nodejs Code output - eae7ec6943953aca94594641523c3c6d
我读过这个答案默认加密算法是 aes-ecb ,它不需要IV。由于密钥长度为16,我假设 aes-128-ecb
(16 * 8 = 128)是我应该使用的算法。
I've read from this answer that by default encryption algorithm is aes-ecb which does not need IV. As the key length is 16, I'm assuming aes-128-ecb
(16*8 = 128) is the algorithm that I should use.
有人能帮我解决问题吗?
Can someone help me figure out the problem ??
推荐答案
只需改变 -
crypto.createCipher('aes-128-ecb',fcKey,);
到
crypto.createCipheriv('aes-128-ecb',fcKey,);
原因很简单 - createCipher
方法将第二个参数视为加密密码
,但它是加密密钥
。
Reason is simple - createCipher
method treats second parameter as Encryption Password
while it is an Encryption Key
.
我的不好,即使在阅读这个答案,我使用了错误的方法(crypto.createCipher而不是crypto.createCipheriv)。下面是nodejs中正确的工作代码。这就是全部所需。
My bad, even after reading this answer, I've used wrong method (crypto.createCipher instead of crypto.createCipheriv). Below is proper working code in nodejs. That was all needed.
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;
}
这篇关于Nodejs Crypto Javascript中的javax.crypto.Cipher等效代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!