跳到主要内容

加密与哈希

加密是一种对信息进行编码的过程。 这个过程将信息的原始表示(称为明文(plaintext))转换为另一种形式,称为密文(ciphertext)。 理想情况下,只有授权的用户才能将密文解密回明文并访问原始信息。 加密本身并不阻止干扰,但它阻止未经授权的拦截者获取可理解的内容。 加密是一个双向函数;通过正确的密钥,加密的内容可以解密。

哈希将给定的密钥转换为另一个值的过程。 哈希函数根据数学算法生成新值。一旦进行了哈希,应该不可能从输出还原到输入。

加密

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

例如,让我们使用AES(高级加密标准)的'aes-256-ctr'算法和CTR加密模式。

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

const iv = randomBytes(16);
const password = '用于生成密钥的密码';

// 密钥长度取决于算法。
// 在这种情况下,对于aes256,它是32字节。
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(),
]);

哈希

对于哈希,我们建议使用bcryptargon2包。 Nest本身没有在这些模块之上提供任何额外的封装,以避免引入不必要的抽象(使学习曲线变短)。

例如,让我们使用bcrypt对一个随机密码进行哈希。

首先安装所需的包:

npm i bcrypt
npm i -D @types/bcrypt

安装完成后,您可以使用hash函数,如下所示:

import * as bcrypt from 'bcrypt';

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

要生成一个盐,请使用genSalt函数:

const salt = await bcrypt.genSalt();

要比较/检查密码,请使用compare函数:

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

您可以在这里阅读更多关于可用函数的信息。