nodejs的crypto加密使用
简单记录一下使用的node加密解密,不是很了解,欢迎指导
pbkdf2Sync
const crypto = require('crypto')
// crypto.pbkdf2Sync()是用来同步生成加密解密密匙的函数
const key = crypto.pbkdf2Sync(pwd, salt, iterations, KEY_SIZE, 'sha1')
// pwd是自定义的作为密匙的字符串
// salt(文档没太看懂,不过也是个字符串,用来生成密匙的)
// iterations 是设置迭代次数的,次数越高生成的密匙越安全
// KEY_SIZE是设置字节长度的(16 或32之类的)
// 'sha1'(这个暂时没搞懂是啥,应该是用来指定什么模式的)
加密
const algorithm = 'aes-128-cbc'
const VIPARA = '1269571869323221'
const UTF_8 = 'utf-8'
const cipherEncoding = 'base64'
// 加密
//crypto.createCipheriv生成一个cipher对象
const cipher = crypto.createCipheriv(algorithm, key, VIPARA)
// algorithm这个是用来指定算法的,
// key就是派生的密匙
// VIPARA是初始化向量,可以空
let encStr = cipher.update(content, UTF_8, cipherEncoding)
// content是你要加密的内容
// 第二个参数指定的是输入的编码格式
// 第三个参数指定的是输出的编码格式
encStr += cipher.final(cipherEncoding)
// cipherEncoding输出的编码格式
console.log('加密', encStr )
解密
// crypto.createDecipheriv这个是生成decipher 对象的
const decipher = crypto.createDecipheriv(algorithm, key, VIPARA)
// algorithm这个是用来指定算法模式的,
// key就是派生的密匙
// VIPARA是初始化向量,不需要的话可以空
let decstr = decipher.update(jeimi, cipherEncoding, UTF_8)
// jeimi是你要解密的内容
// 第二个参数指定的是输入的编码格式
// 第三个参数指定的是输出的编码格式
decstr += decipher.final(UTF_8)
console.log('解密 ', decstr )