小弟不才,请大家赐教: 请问,key与iv是一个什么关系?为什么key改成:123546789,只是长度增加就报ERROR了呢?
var assert = require(‘assert’); var crypto = require(‘crypto’);
function test_des(param) { var key = new Buffer(param.key); var iv = new Buffer(param.iv ? param.iv : 0) var plaintext = param.plaintext var alg = param.alg var autoPad = param.autoPad
//encrypt
var cipher = crypto.createCipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad); //default true
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph += cipher.final('hex');
console.log(alg);
console.log(ciph);
//decrypt
var decipher = crypto.createDecipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad); //default true
var txt = decipher.update(ciph, 'hex', 'utf8');
txt += decipher.final('utf8');
assert.equal(txt, plaintext, 'fail');
console.log(txt);
console.log('----------------------------------------------------');
}
test_des({ alg: 'des-cbc’, autoPad: true, key : '12345678’, plaintext: '123456|123456789’, iv: ‘12345678’ }); 输出: des-cbc cd1fcff886a5ec21c7680f85b627271be05700ab09cc4395 123456|123456789
------------------------------------------------------------------ 但是:
test_des({ alg: 'des-cbc’, autoPad: true, key : '123456789’, plaintext: '123456|123456789’, iv: ‘12345678’ });
ERROR:
node-crypto : Invalid key length 9
crypto.js:315 this._binding.initiv(cipher, toBuf(key), toBuf(iv)); ^ Error: error:0607A082:digital envelope routines:EVP_CIPHER_CTX_set_key_length:invalid key length at new Cipheriv (crypto.js:315:17) at Object.Cipheriv (crypto.js:313:12)