CryptoUtility
Tong quan
CryptoUtility la singleton cung cap cac thao tac mat ma hoc cap ung dung. No bao boc helper AES cua IGNIS Framework (che do AES-256-GCM) va ham hash de cung cap hai kha nang:
- Ma hoa/giai ma doi xung -- su dung
APP_ENV_APPLICATION_SECRETlam khoa, de luu tru du lieu nhay cam nhu thong tin xac thuc thanh toan trong co so du lieu. - Ky HMAC-SHA256 -- de xac minh toan ven payload webhook.
Nguon: packages/core/src/utilities/crypto.utility.ts (53 dong)
Dinh nghia Lop
import { AES, applicationEnvironment, EnvironmentKeys, hash } from '@venizia/ignis';
export interface ISignOptions {
timestamp: number;
eventType: string;
parts: Array<string>;
secret: string;
}
export class CryptoUtility {
private static _instance: CryptoUtility;
private readonly _aes: AES;
private readonly _encryptionKey: string;
private constructor() {
this._aes = AES.withAlgorithm('aes-256-gcm');
this._encryptionKey = applicationEnvironment.get<string>(
EnvironmentKeys.APP_ENV_APPLICATION_SECRET,
);
}
static getInstance(): CryptoUtility;
encrypt(text: string): string;
decrypt(encryptedText: string): string;
sign(opts: ISignOptions): string;
}Cau hinh
| Bien | Bat buoc | Mo ta |
|---|---|---|
APP_ENV_APPLICATION_SECRET | Co | Khoa bi mat dung cho ma hoa AES-256-GCM. Phai duoc dat truoc khi goi CryptoUtility.getInstance(). |
# .env.development
APP_ENV_APPLICATION_SECRET=my-application-secret-key-at-least-32-charsWARNING
APP_ENV_APPLICATION_SECRET duoc su dung lam khoa AES-256-GCM. Neu ban thay doi no, tat ca du lieu da ma hoa truoc do se khong the khoi phuc. Hay doi xu gia tri nay nhu co so ha tang quan trong.
Import
import { CryptoUtility } from '@nx/core';
// or
import { CryptoUtility } from '@nx/core/utilities';API
getInstance()
Tra ve instance singleton. Lan goi dau tien se khoi tao cipher AES voi APP_ENV_APPLICATION_SECRET.
const crypto = CryptoUtility.getInstance();encrypt(text)
Ma hoa chuoi van ban thuan su dung AES-256-GCM voi application secret. Tra ve chuoi ciphertext ma hoa base64 chua IV, ciphertext, va GCM authentication tag.
const crypto = CryptoUtility.getInstance();
const encrypted = crypto.encrypt('my-api-key-12345');
// "base64-encoded-iv+ciphertext+authtag"decrypt(encryptedText)
Giai ma chuoi da ma hoa truoc do ve van ban thuan. Nem loi neu ciphertext bi thay doi (GCM authentication that bai) hoac neu su dung sai khoa.
const crypto = CryptoUtility.getInstance();
const original = crypto.decrypt(encrypted);
// "my-api-key-12345"sign(opts)
Tao chu ky HMAC-SHA256 de xac minh payload webhook. Noi tat ca phan voi | (pipe) va bam voi secret duoc cung cap.
Dinh dang chu ky: timestamp|eventType|part1|part2|... duoc bam voi SHA256, dau ra dang base64.
const crypto = CryptoUtility.getInstance();
const signature = crypto.sign({
timestamp: 1705708800000,
eventType: 'payment.success',
parts: ['txn_abc123', '50000', 'VND'],
secret: 'webhook-shared-secret',
});
// Base64-encoded HMAC-SHA256 of "1705708800000|payment.success|txn_abc123|50000|VND"ISignOptions
| Thuoc tinh | Kieu | Mo ta |
|---|---|---|
timestamp | number | Unix timestamp (mili giay) de bao ve chong phat lai |
eventType | string | Dinh danh loai su kien (vi du: payment.success) |
parts | string[] | Cac phan payload bo sung de dua vao chu ky |
secret | string | Khoa bi mat HMAC (thuong la shared secret cua webhook) |
Tom tat API
| Phuong thuc | Chu ky | Mo ta |
|---|---|---|
getInstance | (): CryptoUtility | Lay instance singleton |
encrypt | (text: string): string | Ma hoa AES-256-GCM voi application secret |
decrypt | (encryptedText: string): string | Giai ma AES-256-GCM voi application secret |
sign | (opts: ISignOptions): string | Ky HMAC-SHA256 mot payload co cau truc |
Vi du Su dung
Ma hoa Thong tin Xac thuc Thanh toan
Goi @nx/payment su dung CryptoUtility de ma hoa thong tin xac thuc nha cung cap thanh toan truoc khi luu vao co so du lieu, va giai ma khi tai cau hinh:
import { CryptoUtility } from '@nx/core';
// Encrypt credentials before storing
const crypto = CryptoUtility.getInstance();
const encryptedApiKey = crypto.encrypt(vnpayApiKey);
const encryptedSecretKey = crypto.encrypt(vnpaySecretKey);
await configurationRepository.create({
data: {
key: 'VNPAY_QR_MMS',
value: JSON.stringify({
apiKey: encryptedApiKey,
secretKey: encryptedSecretKey,
}),
},
});// Decrypt credentials when loading
const config = await configurationRepository.findByKey('VNPAY_QR_MMS');
const parsed = JSON.parse(config.value);
const apiKey = crypto.decrypt(parsed.apiKey);
const secretKey = crypto.decrypt(parsed.secretKey);Ky Payload Webhook
Trinh phat webhook cua @nx/payment su dung sign() de tao chu ky ma nguoi tieu thu webhook co the xac minh:
import { CryptoUtility } from '@nx/core';
const crypto = CryptoUtility.getInstance();
// Generate signature for outgoing webhook
const timestamp = Date.now();
const signature = crypto.sign({
timestamp,
eventType: 'mq-pay:attempt.success',
parts: [transactionId, attemptId, amount.toString()],
secret: webhookConfig.secret,
});
// Include in webhook headers
const headers = {
'X-Webhook-Signature': signature,
'X-Webhook-Timestamp': timestamp.toString(),
};Xac minh Chu ky Webhook Den
Phia nhan, tinh lai chu ky va so sanh:
import { CryptoUtility } from '@nx/core';
function verifyWebhookSignature(req: Request, secret: string): boolean {
const crypto = CryptoUtility.getInstance();
const receivedSignature = req.headers.get('X-Webhook-Signature');
const timestamp = Number(req.headers.get('X-Webhook-Timestamp'));
const body = req.body;
const expectedSignature = crypto.sign({
timestamp,
eventType: body.eventType,
parts: [body.transactionId, body.attemptId, body.amount.toString()],
secret,
});
return receivedSignature === expectedSignature;
}Kien truc
Tham chieu IGNIS Framework
CryptoUtility su dung hai primitive tu IGNIS Framework:
- Lop
AES-- Cung cap ma hoa xac thuc AES-256-GCM. Xem IGNIS Crypto Helper cho API AES day du, bao gom ma hoa file, IV tuy chinh, va cac tuy chon encoding. - Ham
hash()-- Cung cap bam HMAC-SHA256 va MD5. Xem IGNIS Crypto Utility cho chi tiet su dung.