之前项目中要根据用户的id,获取用户的昵称的需求,由于公司的账户信息属于用户平台保管,需要调用他们的api。 他们定义的api需要使用aes-128-cbc加密参数生成sign,需要用到crypto的createCipheriv和createDecipheriv两个方法。就写下了下面的代码

const crypto = require('crypto');

// 加密
function genSign(src, key, iv) {
let sign = '';
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
sign += cipher.update(src, 'utf8', 'hex');
sign += cipher.final('hex');
return sign;
}

// 解密
function deSign(sign, key, iv) {
let src = '';
const cipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
src += cipher.update(sign, 'hex', 'utf8');
src += cipher.final('utf8');
return src;
}


module.exports = { genSign, deSign };

然后调用的过程如下:

// ase-128-cbc 加密算法要求key和iv长度都为16
const key = Buffer.from('9vApxLk5G3PAsJrM', 'utf8');
const iv = Buffer.from('FnJL7EDzjqWjcaY9', 'utf8');
const sign = genSign('hello world', key, iv);
console.log(sign); // 764a669609b0c9b041faeec0d572fd7a


// 解密
const key = Buffer.from('9vApxLk5G3PAsJrM', 'utf8');
const iv = Buffer.from('FnJL7EDzjqWjcaY9', 'utf8');
const src=deSign('764a669609b0c9b041faeec0d572fd7a', key, iv);
console.log(src); // hello world

作者:静xin湖2011