💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 加密和散列 `加密`是一个信息编码的过程。这个过程将原始信息,即明文,转换为密文。理想情况下,只有授权方可以将密文解密为明文。加密本身并不能防止干扰,但是会将可理解内容拒绝给一个可能的拦截器。加密是个双向的函数,包含加密以及使用正确的`key`解密。 `哈希`是一个将给定值转换成另一个值的过程。哈希函数使用数学算法来创建一个新值。一旦哈希完成,是无法从输出值计算回输入值的。 ### 加密 `Node.js`提供了一个内置的[crypto模块](https://nodejs.org/api/crypto.html)可用于加密和解密字符串,数字,Buffer,流等等。Nest未在此基础上提供额外的包以减少不必要的干扰。 一个使用`AES(高级加密系统) aes-256-ctr`算法,CTR加密模式。 ```TypeScript import { createCipheriv, randomBytes } 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`值。 ```TypeScript import { createDecipheriv } from 'crypto'; const decipher = createDecipheriv('aes-256-ctr', key, iv); const decryptedText = Buffer.concat([ decipher.update(encryptedText), decipher.final(), ]); ``` ### 散列 散列方面推荐使用 [bcrypt](https://www.npmjs.com/package/bcrypt) 或 [argon2](https://www.npmjs.com/package/argon2)包. Nest自身并未提供任何这些模块的包装器以减少不必要的抽象(让学习曲线更短)。 例如,使用`bcrypt`来哈希一个随机密码。 首先安装依赖。 ```bash $ npm i bcrypt $ npm i -D @types/bcrypt ``` 依赖安装后,可以使用哈希函数。 ```TypeScript import * as bcrypt from 'bcrypt'; const saltOrRounds = 10; const password = 'random_password'; const hash = await bcrypt.hash(password, saltOrRounds); ``` 使用`genSalt`函数来生成哈希需要的盐。 ```TypeScript const salt = await bcrypt.genSalt(); ``` 使用`compare`函数来比较/检查密码。 ```TypeScript const isMatch = await bcrypt.compare(password, hash); ``` 更多函数参见[这里](https://www.npmjs.com/package/bcrypt)。