UNPKG

@duongtrungnguyen/nestro

Version:
75 lines 2.77 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index); import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs"; import { generateKeyPairSync, sign, verify, constants } from "crypto"; import { Inject, Injectable } from "@nestjs/common"; import { dirname } from "path"; import { debugLog, normalizeJson } from "../../common"; import { KEY_SERVICE_OPTIONS } from "../constants"; let KeyService = class { constructor(options) { this.options = options; if (options.initKeys) this.ensureKeyPair(); } ensureKeyPair() { const keyDir = dirname(this.options.privateKeyPath); if (!existsSync(keyDir)) { debugLog(KeyService.name, "\u{1F4C2} Creating key directory:", keyDir); mkdirSync(keyDir, { recursive: true }); } if (existsSync(this.options.privateKeyPath) && existsSync(this.options.publicKeyPath)) { debugLog(KeyService.name, "Key Pair already exists at:", this.options.privateKeyPath); return; } const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048, publicKeyEncoding: { type: "spki", format: "pem" }, privateKeyEncoding: { type: "pkcs8", format: "pem" } }); writeFileSync(this.options.privateKeyPath, privateKey); writeFileSync(this.options.publicKeyPath, publicKey); debugLog(KeyService.name, "Key Pair generated successfully!"); } getPrivateKey() { return readFileSync(this.options.privateKeyPath, "utf-8"); } getPublicKey() { return readFileSync(this.options.publicKeyPath, "utf-8"); } signData(data) { const privateKey = this.getPrivateKey(); const signObj = sign("sha256", Buffer.from(normalizeJson(data)), { key: privateKey, padding: constants.RSA_PKCS1_PSS_PADDING }); return signObj.toString("base64"); } verifyData(data, signature, publicKey) { return verify( "sha256", Buffer.from(normalizeJson(data)), { key: publicKey, padding: constants.RSA_PKCS1_PSS_PADDING }, Buffer.from(signature, "base64") ); } }; KeyService = __decorateClass([ Injectable(), __decorateParam(0, Inject(KEY_SERVICE_OPTIONS)) ], KeyService); export { KeyService }; //# sourceMappingURL=key.service.js.map