NodeJS

哈希算法

Crypto

代码示例:

// server.js

const crypto = require('crypto')  // 哈希算法

// 单向加密
// const hash = crypto.createHash('sha256')
const hash = crypto.createHmac('sha256', 'foo')  // 第二个实参为密钥值(相当于加盐)

hash.update('Hello World!')  // 支持多次执行

console.log(hash.digest('hex'))
// server02.js

const crypto = require('crypto')

// 对称加密
function encrypt(key, value, data) {  // 加密
    let dep = crypto.createCipheriv('aes-128-cbc', key, value)  // 加密算法与解密算法需要保持一致
    return dep.update(data, 'binary', 'hex') + dep.final('hex')
    // binary:二进制格式,hex:返回十六进制的数据
}

function decrypt(key, value, crypted) {  // 解密
    crypted = Buffer.from(crypted, 'hex').toString('binary')
    let dep = crypto.createDecipheriv('aes-128-cbc', key, value)
    return dep.update(crypted, 'binary', 'utf8') + dep.final('utf8')
}

// 16 * 8 = 128
let key = 'ebc38f2d320a56b9'
let value = 'c240842d7de7beef'

let data = 'foo'

let cryted = encrypt(key, value, data)
console.log('加密:', cryted)

let decrtpted = decrypt(key, value, cryted)
console.log('解密:', decrtpted)