Skip to content

1.hash

哈希函数用于将输入数据转换为固定长度的字符串,通常用于数据完整性校验。SHA-256 是一种常用的哈希算法,输出的哈希值是输入数据的唯一表示。

js
const crypto = require('crypto')

const hash = crypto.createHash('sha256').update('hello world').digest('hex')

console.log(hash)  // 输出 'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda190c6c186c3c3c6c3c6'

2.hmac

HMAC(Hash-based Message Authentication Code)是一种基于哈希函数的消息认证码,用于验证消息的完整性和真实性。它使用一个密钥和哈希函数来生成一个唯一的 HMAC 值。

js
const crypto = require('node:crypto')

const hmac = crypto.createHmac('sha256', 'a secret key')
hmac.update('hello world')

const hmacValue = hmac.digest('hex')
console.log(hmacValue)  // 输出 HMAC 值

3.symmetric-encryption

对称加密使用相同的密钥进行加密和解密。AES(高级加密标准)是一种常用的对称加密算法。初始化向量(IV)用于增强加密的安全性。

js
const crypto = require('node:crypto')

const algorithm = 'aes-256-cbc'
const key = crypto.randomBytes(32) // 32字节密钥
const iv = crypto.randomBytes(16)  // 16字节初始化向量

// 加密
const cipher = crypto.createCipheriv(algorithm, key, iv)
let encrypted = cipher.update('hello world', 'utf8', 'hex')
encrypted += cipher.final('hex')
console.log(encrypted)  // 输出加密后的数据

// 解密
const decipher = crypto.createDecipheriv(algorithm, key, iv)
let decrypted = decipher.update(encrypted, 'hex', 'utf8')
decrypted += decipher.final('utf8')
console.log(decrypted)  // 输出解密后的数据

4.asymmetric-encryption

非对称加密使用一对密钥:公钥和私钥。公钥用于加密数据,私钥用于解密数据。RSA 是一种常用的非对称加密算法,广泛应用于安全通信。

js
const crypto = require('node:crypto')

// 生成密钥对
const { generateKeyPairSync } = crypto
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
  modulusLength: 2048,
})

// 公钥加密
const encryptedData = crypto.publicEncrypt(publicKey, Buffer.from('hello world'))
console.log(encryptedData.toString('hex'))  // 输出加密后的数据

// 私钥解密
const decryptedData = crypto.privateDecrypt(privateKey, encryptedData)
console.log(decryptedData.toString('utf8'))  // 输出解密后的数据