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

我正在尝试将以下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; }