如何将此 Java 代码转换为 JavaScript?
public static String getSignature(String skey, String iv, String data) throws Exception { IvParameterSpec Ⅳ = new IvParameterSpec(iv.getBytes("utf-8")); DESKeySpec desKey = new DESKeySpec(skey.getBytes("utf-8")); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, Ⅳ); byte[] databyte = cipher.doFinal(data.getBytes("utf-8")); return new String(Base64.getEncoder().encode(databyte)); }
我自己尝试了一下,结果是:
function getSignature( skey, iv, data, ) { const IV = Buffer.from(ivString, 'utf-8'); const desKey = Buffer.from(skey, 'utf-8'); const cipher = crypto.createCipheriv('des-cbc', desKey, IV); let encrypted = cipher.update(data, 'utf-8', 'base64'); encrypted += cipher.final('base64'); return encrypted; }
但是我收到了 ERR_CRYPTO_INVALID_KEYLEN
错误,因为我的密钥长度不是 8。我猜测我的 JavaScript 代码缺少这部分 Java 代码,但我不知道如何将这部分翻译成 JavaScript...:
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(desKey);
雷雷