Nodejs - 加密(crypto)

210 阅读1分钟

Crypto 为nodejs自带的插件

1. 使用createCipheriv方法

crypto.createCipheriv( algorithm, key, iv, options )
  • algorithm: 它是一个字符串类型值,取决于OpenSSL。示例是aes192,aes256等。
  • key: 这是算法和iv使用的原始 key 。它包含字符串,Buffer,TypedArray或DataView。 key 可以是可选的secret类型的KeyObject。
    key: 根据选择的算法有关, 比如 aes128、aes192、aes256,长度分别是128、192、256位(16、24、32字节)
  • iv: 它是一个初始化向量,必须是不确定的并且非常独特。但是,理想的iv在密码上是随机的。不必保密。它可以保存字符串,Buffer,TypedArray或DataView类型的数据。如果密码不需要iv,则可以为null。
    iv: 初始化向量,都是128位(16字节),也可以理解为密码盐的一种
  • options: 它是一个可选参数,用于控制流的行为。

2. 编辑

const crypto = require('crypto')

// 密匙
// const key = crypto.randomBytes(192 / 8)
// const iv = crypto.randomBytes(128 / 8)
const key = '0123456789abcdefghijklmn'
const iv = '0123456789abcdef'
const algorithm = 'aes192'
const encoding = 'hex'

// 加密
const encrypt = (content) => {
  const cipher = crypto.createCipheriv(algorithm, key, iv)
  cipher.update(content)
  return cipher.final(encoding)
}


// 解密
const decrypt = (encrypted) => {
  const decipher = crypto.createDecipheriv(algorithm, key, iv)
  decipher.update(encrypted, encoding)
  return decipher.final('utf8')
}

console.log(encrypt('abc123'));

module.exports = {
  encrypt,
  decrypt
}