Java 使用Bouncy Castle和Node.js加密时会出现不同的结果
我尝试在Java(使用Bouncy Castle)和Node.js中执行相同的加密操作,但在每种语言中收到的结果不同。下面是我尝试的实现——有人能发现我哪里出了问题吗 Java代码Java 使用Bouncy Castle和Node.js加密时会出现不同的结果,java,javascript,node.js,cryptography,Java,Javascript,Node.js,Cryptography,我尝试在Java(使用Bouncy Castle)和Node.js中执行相同的加密操作,但在每种语言中收到的结果不同。下面是我尝试的实现——有人能发现我哪里出了问题吗 Java代码 //Java代码: 导入org.bouncycastle.crypto.engines.desedengine; 导入org.bouncycastle.crypto.params.KeyParameter; 导入org.bouncycastle.crypto.*; //... 字符串inputString=“2477
//Java代码:
导入org.bouncycastle.crypto.engines.desedengine;
导入org.bouncycastle.crypto.params.KeyParameter;
导入org.bouncycastle.crypto.*;
//...
字符串inputString=“24778721”//8字节
字符串keyString=“lf9aodkflaen7;ad”;
BufferedBlockCipher cipher=新的BufferedBlockCipher(新的DESedeEngine());
byte[]key=keyString.getBytes();
字节[]输入=inputString.getBytes();
init(isEncode,新的键参数(key));
字节[]结果=新字节[cipher.getOutputSize(input.length)];
int outputLen=cipher.processBytes(输入,0,输入.length,结果,0);
cipher.doFinal(结果,outputLen);
//结果是“65dcbb2e08e6d66e”
JavaScript代码
使用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"
你第二次尝试就快成功了。此代码将为您提供与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
此类问题的第一步是确保在两种环境中使用相同的算法模式和填充。看起来您正在使用Bouncy Castle和Node.js中的默认选项。找出这些默认值是什么。在bouncycastle的源代码中,1)“new BufferedBlockCipher(new DesedEngine())”没有填充处理2)DesedEngine中的块大小是8字节是,但节点有默认的PKCS#7填充。使用双参数
createCipher
方法显然也不起作用。
//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