首先需要安装crypto,命令:npm i crypto --save
1、不可逆加密
const str='1'
let hash = crypto.createHash('md5');
const result = hash.update(str).digest('hex');
const str2 = result.substr(0, 10);
const result2 = hash.update(str2).digest('hex');
console.log(result2);
2、可逆加密
加密:
const password = 'FnJL7EDzjqWjcaY3';
const iv = 'FnJL7EDzjqWjcaY3';
const str='1'
const cipher = crypto.createCipheriv('aes-128-cbc', password, iv);
const result = cipher.update(String(str), 'utf8', 'hex') + cipher.final('hex');
console.log(result); // 91fda3d170e4a8fb6eac97554d04ccf8
解密:
const password = 'FnJL7EDzjqWjcaY3';
const iv = 'FnJL7EDzjqWjcaY3';
const str='91fda3d170e4a8fb6eac97554d04ccf8'
const decipher = crypto.createDecipheriv('aes-128-cbc', password, iv);
const result = decipher.update(String(str), 'hex', 'utf8') + decipher.final('utf8');
console.log(result); //1