这里仅介绍node官网第三种加解密方式:
使用decipher.update()和decipher.final()方法:
yarn add crypto -S 或者 npm i crypto -S
加密
const crypto = require('crypto');
/*
创建一个加密对象
第一个参数: 加密算法(对称算法)
第二个参数: 加解密的私钥
*/
const cipher = crypto.createCipher('aes192', 'hello');
/*
使用加密对象对指定的 字符串进行加密
第一个参数: 要加密的数据
第二个参数: 输入数据的编码格式
第三个格式: 加密的数据格式
*/
let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
//加密对象调用 .final 方法结束加密,阐述加密的结果,指定输出结果为16进制的格式
encrypted += cipher.final('hex');
console.log(encrypted);
解密
//注意因为是对称加密,第二个参数的私要也要与解密一样 也为hello
const decipher = crypto.createDecipher('aes192', 'hello');
//const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
这里的encrypted变量可以拿上边加密的结果encrypted
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted); //some clear text data
crypto.getCiphers() 可以获取多个加密方式 aes192
就是其中之一,可根据场景切换方式,使用方法也相同