加密
是编码信息的过程。 此过程将信息的原始表示形式(称为明文)转换为称为密文的替代形式。 理想情况下,只有授权方才能将密文解密回明文并访问原始信息。 加密本身并不能防止干扰,而是拒绝向可能的拦截器提供可理解的内容。 加密是双向函数; 加密的内容可以用适当的密钥解密。
Node.js 提供了一个内置的 加密模块,你可以使用它来加密和解密字符串、数字、缓冲区、流等。 Nest 本身不在此模块之上提供任何额外的包,以避免引入不必要的抽象。
index.crypto.ts
import { Injectable } from '@nestjs/common';
import * as crypto from 'crypto';
@Injectable()
export class CryptoService {
private readonly secretKey: string = 'my-secret-key'; // 自定义密钥
sign(data: any): string {
const hmac = crypto.createHmac('sha256', this.secretKey);
const payload = JSON.stringify(data);
hmac.update(payload);
return hmac.digest('hex');
}
verify(data: any, signature: string): boolean {
const hmac = crypto.createHmac('sha256', this.secretKey);
const payload = JSON.stringify(data);
hmac.update(payload);
const digest = hmac.digest('hex');
return digest === signature;
}
encrypt(data: any): string {
const cipher = crypto.createCipher('aes256', this.secretKey);
let encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
decrypt(encryptedData: string): any {
const decipher = crypto.createDecipher('aes256', this.secretKey);
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return JSON.parse(decrypted);
}
}
说明:
1. sign(data: any) 方法用于对数据进行签名,返回一个字符串。
2. verify(data: any, signature: string) 方法用于对数据进行校验,返回一个布尔值。
3. encrypt(data: any) 方法用于对数据进行加密,返回一个字符串。
4. decrypt(encryptedData: string) 方法用于对加密数据进行解密,返回一个解密后的原始数据。
使用
import { Body, Controller, Get, Query,Post } from '@nestjs/common';
import { AppService } from './app.service';
import { CryptoService } from './crypto/index.crypto'
import { Public } from './auth/public.guard'
@Controller()
export class AppController {
constructor(private readonly appService: AppService,private readonly cryptoService:CryptoService) {}
@Public()
@Get('crypto')
test() {
const data = { hello: 'world' };
const signature = this.cryptoService.sign(data);
const isValid = this.cryptoService.verify(data, signature);
const encryptedData = this.cryptoService.encrypt(data);
const decryptedData = this.cryptoService.decrypt(encryptedData);
console.log('Signature:', signature);
console.log('Verification:', isValid);
console.log('Encrypted Data:', encryptedData);
console.log('Decrypted Data:', decryptedData);
}
}