英文:
How do you convert this DES encryption code from Java code to JavaScript?
问题
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-cbc', desKey, IV);
let encrypted = cipher.update(data, 'utf-8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
}
英文:
How can I convert this Java code to 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));
}
I tried it myself, and I got:
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;
}
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...:
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(desKey);
答案1
得分: -1
以下是代码的中文翻译部分:
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;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论