NodeJS:如何获得正确的加密结果?

时间:2012-08-23 06:45:18

标签: node.js

我正在使用NodeJS编写DES加密代码。

根据DES算法,结果应该是这样的,

* http://www.unsw.adfa.edu.au/~lpb/src/DEScalc/DEScalc.html

An example DES test value, taken from
"H. Katzan, The Standard Data Encryption Algorithm, pp75-94, Petrocelli Books Inc., New York, 1977" is:

Key:        5B5A57676A56676E (HEX)
Plaintext:  675A69675E5A6B5A (HEX)
Ciphertext: 974AFFBF86022D1F (HEX)

但是,我的代码会打印一些不同的值。

var assert = require("assert");
var crypto = require("crypto");

var plaintext = new Buffer( '675A69675E5A6B5A', 'hex' ).toString( 'binary' );
var key = new Buffer( '5B5A57676A56676E', 'hex' ).toString( 'binary' );

var cipher = crypto.createCipher( 'des-ecb', key );
var c = cipher.update( plaintext, 'binary', 'hex' );
c += cipher.final( 'hex' );

console.log( c );

我应该在上面的代码中修复什么?

1 个答案:

答案 0 :(得分:5)

5B5A57676A56676E是密钥,而不是密码。

var crypto = require("crypto");
var plaintext = new Buffer( '675A69675E5A6B5A', 'hex' ).toString( 'binary' );
console.log("plian:"+plaintext);
var key = new Buffer( '5B5A57676A56676E', 'hex' );
var iv = new Buffer(8);
iv.fill(0);
var cipher = crypto.createCipheriv("des", key, iv);
cipher.setAutoPadding(false);
var c = cipher.update( plaintext, 'binary', 'hex' );
c+=cipher.final('hex' );
console.log(c);