nodejs使用crypto进行des解密,其中key为6位数
nodejs使用crypto进行des解密,其中key为6位数。在使用nodejs与java接口联调过程中,java使用6位的key对数据进行了des加密了,但是node这边一使用java提供的key解密,老是失败,网上看了一下,des加解密的key必须得8位或者其整倍数。
看了一下java端写的加解密方式,原来java空缺的字符 以0来代替了,当然是转换成字节编码后才拼接在后面的。
以下的解密方式是根据6位key来写的,随便写了,懒得优化代码了。
记录一下
var crypto = require('crypto');
var dekey ='123456',
var enkey = '12345678',
var algorithm = { ecb:'des-ecb',cbc:'des-cbc' },
/**
* des加密
* @param plaintext
* @param iv
* @returns {void|Promise<void>|IDBRequest<IDBValidKey>}
*/
function encrypt(plaintext,iv){
var key = new Buffer(this.enkey);
var iv = new Buffer(iv ? iv : 0);
var cipher = crypto.createCipheriv(this.algorithm.ecb, key, iv);
cipher.setAutoPadding(true) //default true
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph += cipher.final('hex');
return ciph;
},
function decrypt(encrypt_text,iv){
// var key = new Buffer(this.dekey,'utf8',8);
var key = Buffer.alloc(8, this.dekey, 'utf8'); // 创建八位的utf8 Unicode 字符数组
var fill = new Buffer(1); //设置默认值为0 Unicode 字符,便于补充空缺的
key[6] = fill; //补充 空缺的 Unicode 字符数组
key[7] = fill; //补充 空缺的 Unicode 字符数组
var iv = new Buffer(iv ? iv : 0); //des-ecb加密,偏移量默认为0就好了,也不能去掉
var decipher = crypto.createDecipheriv(this.algorithm.ecb, key, iv);
decipher.setAutoPadding(true);
var txt = decipher.update(encrypt_text, 'hex', 'utf8');
txt += decipher.final('utf8');
return txt;
}
网友评论