crypto 模块
对内容进行加密
引入
import crypto from 'crypto'
const crypto = require('crypto')
md5
创建
const hash = crypto.createHash('md5')
写入加密内容
hash.update('hello world')
hash.update('more')
sha1
const hash = crypto.createHash('sha1')
hash.update('hello world')
hash.update('more')
hamac
可以指定密匙
const hash = crypto.createHmac('md5', 'mo')
// sha256
hash.update('hello world')
hash.update('more')
aes
加密
const encrypt = (key, iv, data) => {
const dep = crypto.createCipheriv('aes-128-cbc', key, iv)
return dep.update(data, 'binary', 'hex') + dep.final('hex')
}
解密
const decrypt = (key, iv, crypted) => {
crypted = Buffer.from(crypted, 'hex').toString('binary')
const dep = crypto.createDecipheriv('aes-128-cbc', key, iv)
return dep.update(crypted, 'binary', 'utf8') + dep.final('utf8')
}