我正在尝试使用Java(使用Bouncy Castle)和Node.js执行相同的加密操作,但是我在每种语言中都会收到不同的结果。以下是我尝试的实施 - 有人能找到我出错的地方吗?
//Java code:
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.*;
//...
String inputString = "24778721"; //8 bytes
String keyString = "lf9aodkflaen7;ad";
BufferedBlockCipher cipher = new BufferedBlockCipher(new DESedeEngine());
byte[] key = keyString.getBytes();
byte[] input = inputString.getBytes();
cipher.init(isEncode, new KeyParameter(key));
byte[] result = new byte[cipher.getOutputSize(input.length)];
int outputLen = cipher.processBytes(input, 0, input.length, result, 0);
cipher.doFinal(result, outputLen);
//result is "65dcbb2e08e6d66e"
//node.js
var crypto = require('crypto');
var key = "lf9aodkflaen7;ad";
var data = "24778721";
var keybuf = new Buffer(key);
var databuf = new Buffer(data);
var cipher = crypto.createCipher('des-ede', keybuf);
cipher.update(databuf);
var result = cipher.final();
// result is "bf d2 cc 51 c5 e9 ef 38"
替代使用createCipheriv
函数:
var cipher = crypto.createCipheriv('des-ede', keybuf.toString("binary"), '');
cipher.update(databuf);
var result = cipher.final();
// result is "7a 24 bf 56 04 18 e3 6a"
答案 0 :(得分:0)
第二次尝试时差不多了。此代码将为您提供与Bouncy Castle相同的值:
//node.js
var crypto = require('crypto');
var key = "lf9aodkflaen7;ad";
var data = "24778721";
var keybuf = new Buffer(key);
var databuf = new Buffer(data);
var cipher = crypto.createCipheriv('des-ede', keybuf, '');
var crypted = cipher.update(databuf, 'utf8', 'hex');
console.log(crypted);
//65dcbb2e08e6d66e