Skip to content

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:

  1. Ma hoa/giai ma doi xung -- su dung APP_ENV_APPLICATION_SECRET lam khoa, de luu tru du lieu nhay cam nhu thong tin xac thuc thanh toan trong co so du lieu.
  2. Ky HMAC-SHA256 -- de xac minh toan ven payload webhook.

Nguon: packages/core/src/utilities/crypto.utility.ts (53 dong)

Dinh nghia Lop

typescript
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

BienBat buocMo ta
APP_ENV_APPLICATION_SECRETCoKhoa bi mat dung cho ma hoa AES-256-GCM. Phai duoc dat truoc khi goi CryptoUtility.getInstance().
bash
# .env.development
APP_ENV_APPLICATION_SECRET=my-application-secret-key-at-least-32-chars

WARNING

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

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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 tinhKieuMo ta
timestampnumberUnix timestamp (mili giay) de bao ve chong phat lai
eventTypestringDinh danh loai su kien (vi du: payment.success)
partsstring[]Cac phan payload bo sung de dua vao chu ky
secretstringKhoa bi mat HMAC (thuong la shared secret cua webhook)

Tom tat API

Phuong thucChu kyMo ta
getInstance(): CryptoUtilityLay instance singleton
encrypt(text: string): stringMa hoa AES-256-GCM voi application secret
decrypt(encryptedText: string): stringGiai ma AES-256-GCM voi application secret
sign(opts: ISignOptions): stringKy 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:

typescript
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,
    }),
  },
});
typescript
// 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:

typescript
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:

typescript
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.

Tai lieu Lien quan

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.