Crypto
该 node:crypto 模块提供加密功能,包括一组用于 OpenSSL 哈希、HMAC、密码、解密、签名和验证函数的包装器
简单示例:
js
const { createHmac } = require('node:crypto')
const secret = 'lhc'
const hash = createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash, 'hash')
Cipher
该 Cipher 类的实例用于加密数据。该类可以通过以下两种方式之一使用:
- 作为可读和可写的流,其中写入普通未加密数据以在可读端生成加密数据
- 使用
cipher.update()
和cipher.final()
方法生成加密数据
crypto.createCipher()
or crypto.createCipheriv()
方法用于创建 Cipher 实例。 Cipher 不能直接使用 new 关键字创建对象
示例:使用 Cipher 对象流:
js
const { scrypt, randomFill, createCipheriv} = require('node:crypto')
const algorithm = 'aes192'
const password = 'Password used to generate key'
// Scrypt 是一种基于密码的密钥派生函数
scrypt(password, 'salt', 24, (err, key) => {
if(err) throw err
// 此函数类似于 crypto.randomBytes() ,但要求第一个参数是将要填充 Buffer 的参数。它还要求传入回调
// 如果未提供该 callback 函数,则会引发错误
randomFill(new Uint8Array(16), (err, iv) => {
if(err) throw err
// 创建并返回一个 Cipher 对象,该对象使用给定 algorithm 的 和 password
const cipher = createCipheriv(algorithm, key, iv);
// 原始办法获取方法
// let encrypted = '';
// cipher.setEncoding('hex');
// cipher.on('data', (chunk) => encrypted += chunk);
// cipher.on('end', () => console.log(encrypted, '结束'));
// cipher.write('some clear text data');
// cipher.end();
// 示例:使用 cipher.update() 和 cipher.final() 方法:
// 数据 数据的编码 返回值的编码
// cipher.update(data[, inputEncoding][, outputEncoding])
let encrypted = cipher.update('明文数据,账号密码等等', 'utf8', 'hex');
// cipher.final:设置返回值的编码
encrypted += cipher.final('hex');
console.log(encrypted, '加密后')
})
})
Decipher
该 Decipher 类的实例用于解密数据
简单示例:
js
const {
scryptSync,
createDecipheriv,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
const algorithm = 'aes192'
const password = 'Password used to generate key'
const iv = Buffer.alloc(16, 0)
const key = scryptSync(password, 'salt', 24)
const decipher = createDecipheriv(algorithm, key, iv);
const encrypted =
'ae13cdd8f9d8db2e89fe14ef57bbd58e37f443792154e0526a68b31e9386e722ed6d9bfaf17d0ca5de83fb6f1645c826';
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);