UNPKG

afridho-encrypt

Version:

A simple AES encryption and decryption utility

83 lines (82 loc) 2.94 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.decrypt = exports.encrypt = void 0; const CryptoJS = __importStar(require("crypto-js")); const dotenv = __importStar(require("dotenv")); // Load environment variables dotenv.config(); // Ensure ENCRYPT_KEY is defined const ENCRYPT_KEY = process.env.ENCRYPT_KEY; if (!ENCRYPT_KEY) { throw new Error("ENCRYPT_KEY is not defined in the environment variables"); } /** * Encrypts a given text using AES encryption. * * @param text - The plain text to encrypt. * @returns The encrypted text as a base64-encoded string. */ const encrypt = (text) => { if (!text) { throw new Error("Text to encrypt cannot be empty"); } return CryptoJS.AES.encrypt(text, ENCRYPT_KEY).toString(); }; exports.encrypt = encrypt; /** * Decrypts a given AES-encrypted text back to its original plain text. * * @param text - The encrypted text to decrypt. * @returns The decrypted plain text. If decryption fails, returns an empty string. */ const decrypt = (text) => { if (!text) { throw new Error("Encrypted text cannot be empty"); } try { const bytes = CryptoJS.AES.decrypt(text, ENCRYPT_KEY); const decryptedText = bytes.toString(CryptoJS.enc.Utf8); if (!decryptedText) { throw new Error("Decryption failed"); } return decryptedText; } catch (error) { throw new Error("Decryption failed: " + (error instanceof Error ? error.message : "Unknown error")); } }; exports.decrypt = decrypt;