加密和散列

64 阅读1分钟

加密是对信息进行编码的过程。此过程将信息的原始表示形式(称为明文)转换为称为密文的替代形式。

散列是将给定键转换为另一个值的过程。哈希函数用于根据数学算法生成新值。一旦散列完成,就不可能从输出到输入。

加密

Node.js 提供了一个内置的 加密模块,你可以使用它来加密和解密字符串、数字、缓冲区、流等。Nest 本身不在此模块之上提供任何额外的包,以避免引入不必要的抽象。

import { createCipheriv, randomBytes, scrypt } from 'crypto';
import { promisify } from 'util';

const iv = randomBytes(16);
const password = 'Password used to generate key';

// The key length is dependent on the algorithm.
// In this case for aes256, it is 32 bytes.
const key = (await promisify(scrypt)(password, 'salt', 32)) as Buffer;
const cipher = createCipheriv('aes-256-ctr', key, iv);

const textToEncrypt = 'Nest';
const encryptedText = Buffer.concat([
  cipher.update(textToEncrypt),
  cipher.final(),
]);

解密 encryptedText 值

import { createDecipheriv } from 'crypto';

const decipher = createDecipheriv('aes-256-ctr', key, iv);
const decryptedText = Buffer.concat([
  decipher.update(encryptedText),
  decipher.final(),
]);

哈希

对于散列,我们建议使用 bcrypt 或 argon2 包。Nest 本身不在这些模块之上提供任何额外的封装器。

$ npm i bcrypt
$ npm i -D @types/bcrypt
import * as bcrypt from 'bcrypt';

const saltOrRounds = 10;
const password = 'random_password';
const hash = await bcrypt.hash(password, saltOrRounds);

‌bcrypt生成盐‌是一个随机生成的字符串,用于增加密码的安全性。这个盐值在每次密码加密时都会生成一个新的,确保即使密码相同,经过加盐后的哈希值也会不同,从而使得密码更加难以被破解。

// const saltOrRounds = 10;
const saltOrRounds = await bcrypt.genSalt();

要比较/检查密码

const isMatch = await bcrypt.compare(password, hash);