Bagaimanakah cara saya menukar kod penyulitan DES ini daripada kod Java kepada JavaScript?
P粉504080992
P粉504080992 2023-09-06 13:31:17
0
1
586

Bagaimana untuk menukar kod Java ini kepada 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));
}

Saya cuba sendiri dan hasilnya:

  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;
  }

Tetapi saya mendapat ralat ERR_CRYPTO_INVALID_KEYLEN kerana panjang kunci saya bukan 8. Saya rasa kod JavaScript saya tiada bahagian kod Java ini, tetapi saya tidak tahu cara menterjemah bahagian ini kepada JavaScript... :

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  SecretKey key = keyFactory.generateSecret(desKey);

P粉504080992
P粉504080992

membalas semua(1)
P粉550257856
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;
}
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan