UNPKG

@lonewolfspace/storage-manager-ts

Version:

A universal browser storage manager with optional AES encryption support for localStorage, sessionStorage, and cookies.

66 lines (65 loc) 2.63 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Encryption = void 0; const crypto_js_1 = __importDefault(require("crypto-js")); class Encryption { /** * Validate key length (16, 24, or 32 bytes) */ static validateKey(secretKey) { const byteLength = crypto_js_1.default.enc.Utf8.parse(secretKey).sigBytes; const validLengths = [16, 24, 32]; // AES-128, 192, 256 if (!validLengths.includes(byteLength)) { throw new Error(`Invalid secret key length: ${byteLength} bytes. Must be 16, 24, or 32 bytes (128, 192, or 256 bits).`); } } /** * Encrypts a string using AES encryption * @param value The string to encrypt * @param secretKey The secret key for encryption * @returns Encrypted string */ static encrypt(value, secretKey) { if (!value || !secretKey) { throw new Error("Value and secret key are required for encryption"); } this.validateKey(secretKey); const key = crypto_js_1.default.enc.Utf8.parse(secretKey); const encrypted = crypto_js_1.default.AES.encrypt(value, key, { iv: this.DEFAULT_IV, mode: crypto_js_1.default.mode.CBC, padding: crypto_js_1.default.pad.Pkcs7, }); return encrypted.toString(); } /** * Decrypts an encrypted string * @param encryptedValue The encrypted string * @param secretKey The secret key used for encryption * @returns Decrypted string */ static decrypt(encryptedValue, secretKey) { if (!encryptedValue || !secretKey) { throw new Error("Encrypted value and secret key are required for decryption"); } this.validateKey(secretKey); try { const key = crypto_js_1.default.enc.Utf8.parse(secretKey); const decrypted = crypto_js_1.default.AES.decrypt(encryptedValue, key, { iv: this.DEFAULT_IV, mode: crypto_js_1.default.mode.CBC, padding: crypto_js_1.default.pad.Pkcs7, }); return decrypted.toString(crypto_js_1.default.enc.Utf8); } catch (error) { console.log("error: ", error); throw new Error("Failed to decrypt value. Invalid secret key or corrupted data."); } } } exports.Encryption = Encryption; Encryption.DEFAULT_IV = crypto_js_1.default.enc.Hex.parse("00000000000000000000000000000000");