你怎么将这段Java代码转换为JavaScript中的DES加密代码?

huangapple go评论120阅读模式
英文:

How do you convert this DES encryption code from Java code to JavaScript?

问题

  1. const crypto = require('crypto');
  2. function getSignature(skey, iv, data) {
  3. const IV = Buffer.from(iv, 'utf-8');
  4. const desKey = Buffer.from(skey, 'utf-8');
  5. const cipher = crypto.createCipheriv('des-cbc', desKey, IV);
  6. let encrypted = cipher.update(data, 'utf-8', 'base64');
  7. encrypted += cipher.final('base64');
  8. return encrypted;
  9. }
英文:

How can I convert this Java code to JavaScript?

  1. public static String getSignature(String skey, String iv, String data) throws Exception {
  2. IvParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
  3. DESKeySpec desKey = new DESKeySpec(skey.getBytes("utf-8"));
  4. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  5. SecretKey key = keyFactory.generateSecret(desKey);
  6. Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  7. cipher.init(Cipher.ENCRYPT_MODE, key, );
  8. byte[] databyte = cipher.doFinal(data.getBytes("utf-8"));
  9. return new String(Base64.getEncoder().encode(databyte));
  10. }

I tried it myself, and I got:

  1. function getSignature(
  2. skey,
  3. iv,
  4. data,
  5. ) {
  6. const IV = Buffer.from(ivString, 'utf-8');
  7. const desKey = Buffer.from(skey, 'utf-8');
  8. const cipher = crypto.createCipheriv('des-cbc', desKey, IV);
  9. let encrypted = cipher.update(data, 'utf-8', 'base64');
  10. encrypted += cipher.final('base64');
  11. return encrypted;
  12. }

But I got an ERR_CRYPTO_INVALID_KEYLEN error, because my key is not 8 in length. I'm guessing that my JavaScript code is missing this part of the Java code, but I don't know how to translate this part into JavaScript...:

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

答案1

得分: -1

以下是代码的中文翻译部分:

  1. const crypto = require('crypto');
  2. function getSignature(skey, iv, data) {
  3. const IV = Buffer.from(iv, 'utf-8');
  4. const desKey = Buffer.from(skey, 'utf-8');
  5. const cipher = crypto.createCipheriv('des', desKey.slice(0, 8), IV);
  6. let encrypted = cipher.update(data, 'utf-8', 'base64');
  7. encrypted += cipher.final('base64');
  8. return encrypted;
  9. }
英文:
  1. const crypto = require('crypto');
  2. function getSignature(skey, iv, data) {
  3. const IV = Buffer.from(iv, 'utf-8');
  4. const desKey = Buffer.from(skey, 'utf-8');
  5. const cipher = crypto.createCipheriv('des', desKey.slice(0, 8), IV);
  6. let encrypted = cipher.update(data, 'utf-8', 'base64');
  7. encrypted += cipher.final('base64');
  8. return encrypted;
  9. }

huangapple
  • 本文由 发表于 2023年7月3日 16:49:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定