搜尋

首頁  >  問答  >  主體

如何將此 DES 加密程式碼從 Java 程式碼轉換為 JavaScript?

如何將此 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);

P粉504080992P粉504080992447 天前574

全部回覆(1)我來回復

  • P粉550257856

    P粉5502578562023-09-07 10:22:32

    const crypto = require('crypto');
    
    function getSignature(skey, iv, data) {
        const IV = Buffer.from(iv, 'utf-8');
        const desKey = Buffer.from(skey, 'utf-8');
    
        const cipher = crypto.createCipheriv('des', desKey.slice(0, 8), IV);
        let encrypted = cipher.update(data, 'utf-8', 'base64');
        encrypted += cipher.final('base64');
        return encrypted;
    }
    

    回覆
    0
  • 取消回覆