我正在尝试将下面的java代码转换为Nodejs。我有一个要求使用“ DESede”算法使用密钥加密文本。当前代码是用Java编写的,现在我需要迁移到Nodejs
Java代码-
public static void main(String args[]) throws Exception {
String myString = "the sample text to be encrypted";
EncryptData(myString);
}
public static byte[] EncryptData(String text) throws Exception {
String keyValue = "kbhgvfbjhgfcf87576hgv656" ;
final byte[] keyBytes = keyValue.getBytes("UTF8");
final DESedeKeySpec key = new DESedeKeySpec(keyBytes);
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance("DESede");
SecretKey key1 = keyFactory.generateSecret(key);
final Cipher cipher = Cipher.getInstance("DESede");
cipher.init(1, key1);
final byte[] plainTextBytes = text.getBytes("UTF8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return cipherText;
}
我尝试在内置模块Crypto和CryptoJS中同时使用NodeJS。但是得到的结果与我在Java中得到的结果不同。无法弄清楚我所缺少的。
使用CryptoJS [Google代码]-
function encrypt(message, key) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted;
}
使用NodeJS加密-
let option = {
alg: 'des-ede3',
key: "kbhgvfbjhgfcf87576hgv656",
plaintext: "the sample text to be encrypted",
}
encrypt(option);
function encrypt(param) {
var key = new Buffer(param.key, 'utf8');
var plaintext = new Buffer(param.plaintext, 'utf8');
var alg = param.alg;
//encrypt
var cipher = crypto.createCipheriv(alg, key, '');
var ciph = cipher.update(plaintext, 'utf8');
ciph += cipher.final('utf8');
console.log(alg, ciph);
return ciph;
}
我希望输出为-
[-15,6,-31,6,-99,57,-90,-125,121,73,-107,112,-68,8,66,62,116,71,118,- 55,-50,-21,96,-124,63,-75,-96,-117,108,-46,-72]
,但实际输出是- [5a ad e6 65 a1 be b9 68 d5 bd e4 9f 3c ca d6 6c 7e 71 ad 84 c6 39 81 49 14 35 7e 5f de 64 da 40]。