UNPKG

@mercury-labs/hashing

Version:
78 lines 3.31 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HashTextService = void 0; const common_1 = require("@nestjs/common"); const crypto_1 = __importDefault(require("crypto")); let HashTextService = class HashTextService { constructor(_options) { var _a; this._options = _options; this._algorithm = 'aes-256-ctr'; if (!((_a = this._options) === null || _a === void 0 ? void 0 : _a.secretKey) || this._options.secretKey.length !== 32) { throw new common_1.BadRequestException('INVALID_HASHING_SECRET_KEY', 'Secret key is required and should be 32 characters'); } } encode(text) { if (!text || !this._options.enabled || !this._options.secretKey) { return ''; } const iv = crypto_1.default.randomBytes(16); const cipher = crypto_1.default.createCipheriv(this._algorithm, this._options.secretKey, iv); const encrypted = Buffer.concat([cipher.update(text), cipher.final()]); return Buffer.from(JSON.stringify({ iv: iv.toString('hex'), content: encrypted.toString('hex'), })).toString('base64'); } decode(hashedText) { if (!hashedText || !this._options.enabled || !this._options.secretKey) { return ''; } try { const hash = JSON.parse(Buffer.from(hashedText, 'base64').toString('utf-8')); const decipher = crypto_1.default.createDecipheriv(this._algorithm, this._options.secretKey, Buffer.from(hash.iv, 'hex')); return Buffer.concat([ decipher.update(Buffer.from(hash.content, 'hex')), decipher.final(), ]).toString(); } catch { return undefined; } } encodeJSON(obj) { try { return this.encode(JSON.stringify(obj)); } catch { return undefined; } } decodeJSON(hashedObj) { try { const decodedText = this.decode(hashedObj); return decodedText ? JSON.parse(decodedText) : undefined; } catch { return undefined; } } }; HashTextService = __decorate([ (0, common_1.Injectable)(), __metadata("design:paramtypes", [Object]) ], HashTextService); exports.HashTextService = HashTextService; //# sourceMappingURL=hash-text.service.js.map