| import * as crypto from 'node:crypto'; | ||
| /** | ||
| * @class AsimetricUtils | ||
| * @classdesc A utility class for asymmetric encryption using RSA. | ||
| * Provides functions for generating, storing, retrieving, encrypting, and decrypting data securely. | ||
| */ | ||
| declare class AsimetricUtils { | ||
| /** | ||
| * Generates an RSA key pair (public and private keys). | ||
| * | ||
| * @param {number} keySize - The size of the RSA key in bits (recommended: 2048 or 4096). | ||
| * @returns {{ publicKey: string, privateKey: string }} An object containing the keys in PEM format. | ||
| * @throws {Error} If key generation fails. | ||
| * @example | ||
| * // Generate a 2048-bit RSA key pair | ||
| * const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| * console.log("Public Key:\n", keys.publicKey); | ||
| * console.log("Private Key:\n", keys.privateKey); | ||
| */ | ||
| static generateRSAKeyPair(keySize: number): { | ||
| publicKey: string; | ||
| privateKey: string; | ||
| }; | ||
| /** | ||
| * Saves a public key to a file. | ||
| * | ||
| * @param {string} publicKey - The public key in PEM format. | ||
| * @param {string} filePath - The file path where the key should be saved. | ||
| * @throws {Error} If the file cannot be written. | ||
| * @example | ||
| * const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| * AsimetricUtils.savePublicKey(keys.publicKey, './public.pem'); | ||
| * console.log("Public key saved successfully!"); | ||
| */ | ||
| static savePublicKey(publicKey: string, filePath: string): void; | ||
| /** | ||
| * Loads a public key from a file. | ||
| * | ||
| * @param {string} filePath - The path of the file containing the public key. | ||
| * @returns {crypto.KeyObject} The loaded public key. | ||
| * @throws {Error} If the file cannot be read. | ||
| * @example | ||
| * const publicKey = AsimetricUtils.loadPublicKey('./public.pem'); | ||
| * console.log("Loaded Public Key:\n", publicKey); | ||
| */ | ||
| static loadPublicKey(filePath: string): crypto.KeyObject; | ||
| /** | ||
| * Saves a private key to a file. | ||
| * | ||
| * @param {string} privateKey - The private key in PEM format. | ||
| * @param {string} filePath - The file path where the key should be saved. | ||
| * @throws {Error} If the file cannot be written. | ||
| * @example | ||
| * const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| * AsimetricUtils.savePrivateKey(keys.privateKey, './private.pem'); | ||
| * console.log("Private key saved successfully!"); | ||
| */ | ||
| static savePrivateKey(privateKey: string, filePath: string): void; | ||
| /** | ||
| * Loads a private key from a file. | ||
| * | ||
| * @param {string} filePath - The path of the file containing the private key. | ||
| * @returns {crypto.KeyObject} The loaded private key. | ||
| * @throws {Error} If the file cannot be read. | ||
| * @example | ||
| * const privateKey = AsimetricUtils.loadPrivateKey('./private.pem'); | ||
| * console.log("Loaded Private Key:\n", privateKey); | ||
| */ | ||
| static loadPrivateKey(filePath: string): crypto.KeyObject; | ||
| /** | ||
| * Encrypts a message using a public key. | ||
| * | ||
| * @param {string} data - The plaintext message to encrypt. | ||
| * @param {crypto.KeyObject} publicKey - The public key used for encryption. | ||
| * @returns {Buffer} The encrypted message. | ||
| * @throws {Error} If encryption fails. | ||
| * @example | ||
| * const publicKey = AsimetricUtils.loadPublicKey('./public.pem'); | ||
| * const encrypted = AsimetricUtils.encryptWithPublicKey("Hello, World!", publicKey); | ||
| * console.log("Encrypted Data:", encrypted.toString('base64')); | ||
| */ | ||
| static encryptWithPublicKey(data: string, publicKey: crypto.KeyObject): Buffer; | ||
| /** | ||
| * Decrypts a message using a private key. | ||
| * | ||
| * @param {Buffer} encryptedData - The encrypted data. | ||
| * @param {crypto.KeyObject} privateKey - The private key used for decryption. | ||
| * @returns {string} The decrypted message. | ||
| * @throws {Error} If decryption fails. | ||
| * @example | ||
| * const privateKey = AsimetricUtils.loadPrivateKey('./private.pem'); | ||
| * const decrypted = AsimetricUtils.decryptWithPrivateKey(encryptedData, privateKey); | ||
| * console.log("Decrypted Message:", decrypted); | ||
| */ | ||
| static decryptWithPrivateKey(encryptedData: Buffer, privateKey: crypto.KeyObject): string; | ||
| } | ||
| export default AsimetricUtils; | ||
| //# sourceMappingURL=AsimetricUtils.d.ts.map |
| {"version":3,"file":"AsimetricUtils.d.ts","sourceRoot":"","sources":["../src/AsimetricUtils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAEtC;;;;GAIG;AACH,cAAM,cAAc;IAChB;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE;IAerF;;;;;;;;;;OAUG;IACH,MAAM,CAAC,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAQ/D;;;;;;;;;OASG;IACH,MAAM,CAAC,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,SAAS;IASxD;;;;;;;;;;OAUG;IACH,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAQjE;;;;;;;;;OASG;IACH,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,SAAS;IASzD;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,GAAG,MAAM;IAc9E;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,qBAAqB,CAAC,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,SAAS,GAAG,MAAM;CAc5F;AAED,eAAe,cAAc,CAAC"} |
| "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 }); | ||
| const fs = __importStar(require("node:fs")); | ||
| const crypto = __importStar(require("node:crypto")); | ||
| /** | ||
| * @class AsimetricUtils | ||
| * @classdesc A utility class for asymmetric encryption using RSA. | ||
| * Provides functions for generating, storing, retrieving, encrypting, and decrypting data securely. | ||
| */ | ||
| class AsimetricUtils { | ||
| /** | ||
| * Generates an RSA key pair (public and private keys). | ||
| * | ||
| * @param {number} keySize - The size of the RSA key in bits (recommended: 2048 or 4096). | ||
| * @returns {{ publicKey: string, privateKey: string }} An object containing the keys in PEM format. | ||
| * @throws {Error} If key generation fails. | ||
| * @example | ||
| * // Generate a 2048-bit RSA key pair | ||
| * const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| * console.log("Public Key:\n", keys.publicKey); | ||
| * console.log("Private Key:\n", keys.privateKey); | ||
| */ | ||
| static generateRSAKeyPair(keySize) { | ||
| try { | ||
| const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { | ||
| modulusLength: keySize, | ||
| }); | ||
| return { | ||
| publicKey: publicKey.export({ type: 'spki', format: 'pem' }).toString(), | ||
| privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), | ||
| }; | ||
| } | ||
| catch (error) { | ||
| throw new Error("Failed to generate RSA key pair: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Saves a public key to a file. | ||
| * | ||
| * @param {string} publicKey - The public key in PEM format. | ||
| * @param {string} filePath - The file path where the key should be saved. | ||
| * @throws {Error} If the file cannot be written. | ||
| * @example | ||
| * const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| * AsimetricUtils.savePublicKey(keys.publicKey, './public.pem'); | ||
| * console.log("Public key saved successfully!"); | ||
| */ | ||
| static savePublicKey(publicKey, filePath) { | ||
| try { | ||
| fs.writeFileSync(filePath, publicKey); | ||
| } | ||
| catch (error) { | ||
| throw new Error("Failed to save public key: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Loads a public key from a file. | ||
| * | ||
| * @param {string} filePath - The path of the file containing the public key. | ||
| * @returns {crypto.KeyObject} The loaded public key. | ||
| * @throws {Error} If the file cannot be read. | ||
| * @example | ||
| * const publicKey = AsimetricUtils.loadPublicKey('./public.pem'); | ||
| * console.log("Loaded Public Key:\n", publicKey); | ||
| */ | ||
| static loadPublicKey(filePath) { | ||
| try { | ||
| const pemPublicKey = fs.readFileSync(filePath, 'utf8'); | ||
| return crypto.createPublicKey(pemPublicKey); | ||
| } | ||
| catch (error) { | ||
| throw new Error("Failed to load public key: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Saves a private key to a file. | ||
| * | ||
| * @param {string} privateKey - The private key in PEM format. | ||
| * @param {string} filePath - The file path where the key should be saved. | ||
| * @throws {Error} If the file cannot be written. | ||
| * @example | ||
| * const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| * AsimetricUtils.savePrivateKey(keys.privateKey, './private.pem'); | ||
| * console.log("Private key saved successfully!"); | ||
| */ | ||
| static savePrivateKey(privateKey, filePath) { | ||
| try { | ||
| fs.writeFileSync(filePath, privateKey); | ||
| } | ||
| catch (error) { | ||
| throw new Error("Failed to save private key: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Loads a private key from a file. | ||
| * | ||
| * @param {string} filePath - The path of the file containing the private key. | ||
| * @returns {crypto.KeyObject} The loaded private key. | ||
| * @throws {Error} If the file cannot be read. | ||
| * @example | ||
| * const privateKey = AsimetricUtils.loadPrivateKey('./private.pem'); | ||
| * console.log("Loaded Private Key:\n", privateKey); | ||
| */ | ||
| static loadPrivateKey(filePath) { | ||
| try { | ||
| const pemPrivateKey = fs.readFileSync(filePath, 'utf8'); | ||
| return crypto.createPrivateKey(pemPrivateKey); | ||
| } | ||
| catch (error) { | ||
| throw new Error("Failed to load private key: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Encrypts a message using a public key. | ||
| * | ||
| * @param {string} data - The plaintext message to encrypt. | ||
| * @param {crypto.KeyObject} publicKey - The public key used for encryption. | ||
| * @returns {Buffer} The encrypted message. | ||
| * @throws {Error} If encryption fails. | ||
| * @example | ||
| * const publicKey = AsimetricUtils.loadPublicKey('./public.pem'); | ||
| * const encrypted = AsimetricUtils.encryptWithPublicKey("Hello, World!", publicKey); | ||
| * console.log("Encrypted Data:", encrypted.toString('base64')); | ||
| */ | ||
| static encryptWithPublicKey(data, publicKey) { | ||
| try { | ||
| return crypto.publicEncrypt({ | ||
| key: publicKey, | ||
| padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, | ||
| }, Buffer.from(data)); | ||
| } | ||
| catch (error) { | ||
| throw new Error("Failed to encrypt with public key: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Decrypts a message using a private key. | ||
| * | ||
| * @param {Buffer} encryptedData - The encrypted data. | ||
| * @param {crypto.KeyObject} privateKey - The private key used for decryption. | ||
| * @returns {string} The decrypted message. | ||
| * @throws {Error} If decryption fails. | ||
| * @example | ||
| * const privateKey = AsimetricUtils.loadPrivateKey('./private.pem'); | ||
| * const decrypted = AsimetricUtils.decryptWithPrivateKey(encryptedData, privateKey); | ||
| * console.log("Decrypted Message:", decrypted); | ||
| */ | ||
| static decryptWithPrivateKey(encryptedData, privateKey) { | ||
| try { | ||
| const decrypted = crypto.privateDecrypt({ | ||
| key: privateKey, | ||
| padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, | ||
| }, encryptedData); | ||
| return decrypted.toString(); | ||
| } | ||
| catch (error) { | ||
| throw new Error("Failed to decrypt with private key: " + error.message); | ||
| } | ||
| } | ||
| } | ||
| exports.default = AsimetricUtils; | ||
| //# sourceMappingURL=AsimetricUtils.js.map |
| {"version":3,"file":"AsimetricUtils.js","sourceRoot":"","sources":["../src/AsimetricUtils.ts"],"names":[],"mappings":"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"} |
| export {}; | ||
| //# sourceMappingURL=Cryptix.d.ts.map |
| {"version":3,"file":"Cryptix.d.ts","sourceRoot":"","sources":["../src/Cryptix.ts"],"names":[],"mappings":""} |
+211
| "use strict"; | ||
| var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
| function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
| return new (P || (P = Promise))(function (resolve, reject) { | ||
| function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
| function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
| function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
| step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
| }); | ||
| }; | ||
| var __importDefault = (this && this.__importDefault) || function (mod) { | ||
| return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| const Encryptor_1 = __importDefault(require("../src/Encryptor")); | ||
| const Decryptor_1 = __importDefault(require("../src/Decryptor")); | ||
| const HashingUtils_1 = __importDefault(require("../src/HashingUtils")); | ||
| const KeyGenerator_1 = __importDefault(require("../src/KeyGenerator")); | ||
| const SecurityUtils_1 = __importDefault(require("../src/SecurityUtils")); | ||
| const AsimetricUtils_1 = __importDefault(require("../src/AsimetricUtils")); | ||
| // Clase Cryptix que ofrece operaciones de criptografía | ||
| class Cryptix { | ||
| // Métodos de Encriptación y Desencriptación | ||
| /** | ||
| * Encripta un texto plano utilizando un password y AES-GCM. | ||
| * @param {string} plainText - El texto que se desea encriptar. | ||
| * @param {string} password - La contraseña utilizada para la encriptación. | ||
| * @return {string} El texto encriptado en formato Base64. | ||
| */ | ||
| static encrypt(plainText, password) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield Encryptor_1.default.encrypt(plainText, password); | ||
| }); | ||
| } | ||
| /** | ||
| * Desencripta un texto previamente encriptado utilizando un password y AES-GCM. | ||
| * @param {string} encryptedText - El texto encriptado que se desea desencriptar. | ||
| * @param {string} password - La contraseña utilizada para la desencriptación. | ||
| * @return {string | undefined} El texto desencriptado o undefined si ocurre un error. | ||
| */ | ||
| static decrypt(encryptedText, password) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield Decryptor_1.default.decrypt(encryptedText, password); | ||
| }); | ||
| } | ||
| // Métodos de Hashing | ||
| /** | ||
| * Genera un hash SHA-512 del texto proporcionado. | ||
| * @param {string} input - El texto plano para el cual se genera el hash. | ||
| * @return {string} El hash SHA-512 generado en formato Base64. | ||
| */ | ||
| static generateSHA512Hash(input) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield HashingUtils_1.default.generateSecureHashSHA512(input); | ||
| }); | ||
| } | ||
| /** | ||
| * Genera un hash SHA-256 del texto proporcionado. | ||
| * @param {string} input - El texto plano para el cual se genera el hash. | ||
| * @return {string} El hash SHA-256 generado en formato Base64. | ||
| */ | ||
| static generateSHA256Hash(input) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield HashingUtils_1.default.generateSecureHashSHA256(input); | ||
| }); | ||
| } | ||
| /** | ||
| * Verifica si el texto proporcionado corresponde al hash dado con SHA-512. | ||
| * @param {string} hash - El hash previamente generado. | ||
| * @param {string} textPlain - El texto plano que se desea verificar. | ||
| * @return {boolean} true si el texto corresponde al hash, false en caso contrario. | ||
| */ | ||
| static hash512IsValid(hash, textPlain) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield HashingUtils_1.default.verifyHashSHA512(textPlain, hash); | ||
| }); | ||
| } | ||
| /** | ||
| * Verifica si el texto proporcionado corresponde al hash dado con SHA-256. | ||
| * @param {string} hash - El hash previamente generado. | ||
| * @param {string} textPlain - El texto plano que se desea verificar. | ||
| * @return {boolean} true si el texto corresponde al hash, false en caso contrario. | ||
| */ | ||
| static hash256IsValid(hash, textPlain) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield HashingUtils_1.default.verifyHashSHA256(textPlain, hash); | ||
| }); | ||
| } | ||
| // Métodos de Generación de Claves y Sal | ||
| /** | ||
| * Genera una clave secreta a partir de una contraseña y un salt utilizando un algoritmo derivado. | ||
| * @param {string} password - La contraseña utilizada para generar la clave. | ||
| * @param {Buffer} salt - El salt utilizado en la generación de la clave. | ||
| * @return {Promise<Buffer>} La clave generada. | ||
| */ | ||
| static generateKey(password, salt) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield KeyGenerator_1.default.generateKey(password, salt); | ||
| }); | ||
| } | ||
| /** | ||
| * Genera un salt aleatorio para ser utilizado en la encriptación o hashing. | ||
| * @return {Buffer} Un array de bytes que representa un salt aleatorio. | ||
| */ | ||
| static generateSalt() { | ||
| return KeyGenerator_1.default.generateSalt(); | ||
| } | ||
| // Métodos de HMAC (Hashed Message Authentication Code) | ||
| /** | ||
| * Genera un HMAC utilizando HmacSHA512. | ||
| * @param {string} message - El mensaje que se va a autenticar. | ||
| * @param {string} secretKey - La clave secreta utilizada para generar el HMAC. | ||
| * @return {string | undefined} El HMAC generado en formato Base64 o undefined si ocurre un error. | ||
| */ | ||
| static generateHMAC(message, secretKey) { | ||
| return SecurityUtils_1.default.generateHMAC(message, secretKey); | ||
| } | ||
| /** | ||
| * Verifica si un HMAC recibido coincide con el HMAC generado a partir del mensaje y la clave secreta. | ||
| * @param {string} message - El mensaje original. | ||
| * @param {string} secretKey - La clave secreta utilizada. | ||
| * @param {string} receivedHMAC - El HMAC recibido que se desea verificar. | ||
| * @return {boolean} true si el HMAC coincide, de lo contrario false. | ||
| */ | ||
| static verifyHMAC(message, secretKey, receivedHMAC) { | ||
| return SecurityUtils_1.default.verifyHMAC(message, secretKey, receivedHMAC); | ||
| } | ||
| /** | ||
| * Genera una clave secreta aleatoria en Base64 para su uso en HMAC. | ||
| * @return {string} Clave secreta aleatoria en formato Base64. | ||
| */ | ||
| static generateRandomKey() { | ||
| return SecurityUtils_1.default.generateRandomKey(); | ||
| } | ||
| // Métodos de Encriptación Asimétrica | ||
| /** | ||
| * Genera un par de claves pública y privada utilizando RSA. | ||
| * @param {number} keySize - El tamaño de la clave en bits (por ejemplo, 2048). | ||
| * @return {Promise<KeyPair>} Un par de claves RSA (pública y privada). | ||
| */ | ||
| static generateRSAKeyPair(keySize) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield AsimetricUtils_1.default.generateRSAKeyPair(keySize); | ||
| }); | ||
| } | ||
| /** | ||
| * Encripta datos utilizando la clave pública RSA. | ||
| * @param {string} data - El texto plano que se desea encriptar. | ||
| * @param {PublicKey} publicKey - La clave pública utilizada para la encriptación. | ||
| * @return {Promise<Buffer>} Los datos encriptados. | ||
| */ | ||
| static encryptWithPublicKey(data, publicKey) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield AsimetricUtils_1.default.encryptWithPublicKey(data, publicKey); | ||
| }); | ||
| } | ||
| /** | ||
| * Desencripta datos utilizando la clave privada RSA. | ||
| * @param {Buffer} encryptedData - Los datos encriptados que se desean desencriptar. | ||
| * @param {PrivateKey} privateKey - La clave privada utilizada para la desencriptación. | ||
| * @return {Promise<string>} El texto desencriptado. | ||
| */ | ||
| static decryptWithPrivateKey(encryptedData, privateKey) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield AsimetricUtils_1.default.decryptWithPrivateKey(encryptedData, privateKey); | ||
| }); | ||
| } | ||
| // Métodos de Guardado y Carga de Claves | ||
| /** | ||
| * Guarda la clave pública en un archivo. | ||
| * @param {PublicKey} publicKey - La clave pública que se desea guardar. | ||
| * @param {string} filePath - La ruta del archivo donde se guardará la clave pública. | ||
| */ | ||
| static savePublicKey(publicKey, filePath) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield AsimetricUtils_1.default.savePublicKey(publicKey, filePath); | ||
| }); | ||
| } | ||
| /** | ||
| * Carga la clave pública desde un archivo. | ||
| * @param {string} filePath - La ruta del archivo desde donde se cargará la clave pública. | ||
| * @return {Promise<PublicKey>} La clave pública cargada. | ||
| */ | ||
| static loadPublicKey(filePath) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield AsimetricUtils_1.default.loadPublicKey(filePath); | ||
| }); | ||
| } | ||
| /** | ||
| * Guarda la clave privada en un archivo. | ||
| * @param {PrivateKey} privateKey - La clave privada que se desea guardar. | ||
| * @param {string} filePath - La ruta del archivo donde se guardará la clave privada. | ||
| */ | ||
| static savePrivateKey(privateKey, filePath) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield AsimetricUtils_1.default.savePrivateKey(privateKey, filePath); | ||
| }); | ||
| } | ||
| /** | ||
| * Carga la clave privada desde un archivo. | ||
| * @param {string} filePath - La ruta del archivo desde donde se cargará la clave privada. | ||
| * @return {Promise<PrivateKey>} La clave privada cargada. | ||
| */ | ||
| static loadPrivateKey(filePath) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return yield AsimetricUtils_1.default.loadPrivateKey(filePath); | ||
| }); | ||
| } | ||
| } | ||
| module.exports = Cryptix; | ||
| //# sourceMappingURL=Cryptix.js.map |
| {"version":3,"file":"Cryptix.js","sourceRoot":"","sources":["../src/Cryptix.ts"],"names":[],"mappings":"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"} |
| /** | ||
| * @class Decryptor | ||
| * @classdesc Utility class for decrypting AES-GCM encrypted data using a password-derived key. | ||
| */ | ||
| declare class Decryptor { | ||
| /** Number of PBKDF2 iterations for key derivation (higher = more secure but slower). */ | ||
| static ITERATIONS: number; | ||
| /** Salt length in bytes (16 bytes = 128 bits, recommended for security). */ | ||
| static SALT_LENGTH: number; | ||
| /** Key length in bytes (32 bytes = 256 bits, AES-256). */ | ||
| static KEY_LENGTH: number; | ||
| /** Initialization Vector (IV) length in bytes (12 bytes is recommended for AES-GCM). */ | ||
| static IV_LENGTH: number; | ||
| /** Authentication Tag length in bytes (16 bytes ensures message integrity). */ | ||
| static AUTH_TAG_LENGTH: number; | ||
| /** | ||
| * Decrypts an AES-GCM encrypted message using a password. | ||
| * | ||
| * @param {string} encryptedText - The Base64-encoded encrypted string (contains salt + IV + cipherText + authTag). | ||
| * @param {string} password - The password used to derive the decryption key. | ||
| * @returns {string | undefined} - The decrypted plaintext string, or `undefined` if decryption fails. | ||
| * @throws {Error} If decryption fails. | ||
| * | ||
| * @example | ||
| * const decrypted = Decryptor.decrypt(encryptedData, "my_secure_password"); | ||
| * console.log("Decrypted Text:", decrypted); | ||
| */ | ||
| static decrypt(encryptedText: string, password: string): string | undefined; | ||
| } | ||
| export default Decryptor; | ||
| //# sourceMappingURL=Decryptor.d.ts.map |
| {"version":3,"file":"Decryptor.d.ts","sourceRoot":"","sources":["../src/Decryptor.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,cAAM,SAAS;IACX,wFAAwF;IACxF,MAAM,CAAC,UAAU,EAAE,MAAM,CAAS;IAElC,4EAA4E;IAC5E,MAAM,CAAC,WAAW,EAAE,MAAM,CAAM;IAEhC,0DAA0D;IAC1D,MAAM,CAAC,UAAU,EAAE,MAAM,CAAM;IAE/B,wFAAwF;IACxF,MAAM,CAAC,SAAS,EAAE,MAAM,CAAM;IAE9B,+EAA+E;IAC/E,MAAM,CAAC,eAAe,EAAE,MAAM,CAAM;IAEpC;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,OAAO,CAAC,aAAa,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;CA6B9E;AAED,eAAe,SAAS,CAAC"} |
| "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 }); | ||
| const crypto = __importStar(require("node:crypto")); | ||
| /** | ||
| * @class Decryptor | ||
| * @classdesc Utility class for decrypting AES-GCM encrypted data using a password-derived key. | ||
| */ | ||
| class Decryptor { | ||
| /** | ||
| * Decrypts an AES-GCM encrypted message using a password. | ||
| * | ||
| * @param {string} encryptedText - The Base64-encoded encrypted string (contains salt + IV + cipherText + authTag). | ||
| * @param {string} password - The password used to derive the decryption key. | ||
| * @returns {string | undefined} - The decrypted plaintext string, or `undefined` if decryption fails. | ||
| * @throws {Error} If decryption fails. | ||
| * | ||
| * @example | ||
| * const decrypted = Decryptor.decrypt(encryptedData, "my_secure_password"); | ||
| * console.log("Decrypted Text:", decrypted); | ||
| */ | ||
| static decrypt(encryptedText, password) { | ||
| try { | ||
| // 1️⃣ Convert Base64 encrypted string to Buffer | ||
| const encryptedData = Buffer.from(encryptedText, "base64"); | ||
| // 2️⃣ Extract components from the encrypted data | ||
| const salt = encryptedData.subarray(0, Decryptor.SALT_LENGTH); | ||
| const iv = encryptedData.subarray(Decryptor.SALT_LENGTH, Decryptor.SALT_LENGTH + Decryptor.IV_LENGTH); | ||
| const cipherText = encryptedData.subarray(Decryptor.SALT_LENGTH + Decryptor.IV_LENGTH, encryptedData.length - Decryptor.AUTH_TAG_LENGTH); | ||
| const authTag = encryptedData.subarray(encryptedData.length - Decryptor.AUTH_TAG_LENGTH); | ||
| // 3️⃣ Derive the encryption key using PBKDF2 | ||
| const key = crypto.pbkdf2Sync(password, salt, Decryptor.ITERATIONS, Decryptor.KEY_LENGTH, "sha256"); | ||
| // 4️⃣ Create AES-GCM decipher instance | ||
| const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv); | ||
| decipher.setAuthTag(authTag); | ||
| // 5️⃣ Decrypt the ciphertext | ||
| let decryptedText = decipher.update(cipherText); | ||
| decryptedText = Buffer.concat([decryptedText, decipher.final()]); | ||
| // 6️⃣ Return the decrypted message as a UTF-8 string | ||
| return decryptedText.toString("utf8"); | ||
| } | ||
| catch (error) { | ||
| throw new Error("Decryption failed: " + (error instanceof Error ? error.message : "Unknown error")); | ||
| } | ||
| } | ||
| } | ||
| /** Number of PBKDF2 iterations for key derivation (higher = more secure but slower). */ | ||
| Decryptor.ITERATIONS = 10000; | ||
| /** Salt length in bytes (16 bytes = 128 bits, recommended for security). */ | ||
| Decryptor.SALT_LENGTH = 16; | ||
| /** Key length in bytes (32 bytes = 256 bits, AES-256). */ | ||
| Decryptor.KEY_LENGTH = 32; | ||
| /** Initialization Vector (IV) length in bytes (12 bytes is recommended for AES-GCM). */ | ||
| Decryptor.IV_LENGTH = 12; | ||
| /** Authentication Tag length in bytes (16 bytes ensures message integrity). */ | ||
| Decryptor.AUTH_TAG_LENGTH = 16; | ||
| exports.default = Decryptor; | ||
| //# sourceMappingURL=Decryptor.js.map |
| {"version":3,"file":"Decryptor.js","sourceRoot":"","sources":["../src/Decryptor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAsC;AAEtC;;;GAGG;AACH,MAAM,SAAS;IAgBX;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,OAAO,CAAC,aAAqB,EAAE,QAAgB;QAClD,IAAI,CAAC;YACD,gDAAgD;YAChD,MAAM,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;YAE3D,iDAAiD;YACjD,MAAM,IAAI,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,CAAC,WAAW,CAAC,CAAC;YAC9D,MAAM,EAAE,GAAG,aAAa,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,CAAC,WAAW,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;YACtG,MAAM,UAAU,GAAG,aAAa,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,GAAG,SAAS,CAAC,SAAS,EAAE,aAAa,CAAC,MAAM,GAAG,SAAS,CAAC,eAAe,CAAC,CAAC;YACzI,MAAM,OAAO,GAAG,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC,MAAM,GAAG,SAAS,CAAC,eAAe,CAAC,CAAC;YAEzF,6CAA6C;YAC7C,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,SAAS,CAAC,UAAU,EAAE,SAAS,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;YAEpG,uCAAuC;YACvC,MAAM,QAAQ,GAAG,MAAM,CAAC,gBAAgB,CAAC,aAAa,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;YACjE,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;YAE7B,6BAA6B;YAC7B,IAAI,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;YAChD,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,aAAa,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;YAEjE,qDAAqD;YACrD,OAAO,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAE1C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,qBAAqB,GAAG,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC;QACxG,CAAC;IACL,CAAC;;AAvDD,wFAAwF;AACjF,oBAAU,GAAW,KAAK,CAAC;AAElC,4EAA4E;AACrE,qBAAW,GAAW,EAAE,CAAC;AAEhC,0DAA0D;AACnD,oBAAU,GAAW,EAAE,CAAC;AAE/B,wFAAwF;AACjF,mBAAS,GAAW,EAAE,CAAC;AAE9B,+EAA+E;AACxE,yBAAe,GAAW,EAAE,CAAC;AA6CxC,kBAAe,SAAS,CAAC"} |
| /** | ||
| * @class EncryptFile | ||
| * @classdesc Utility class for encrypting files using a combination of random per-file keys and a fixed secret key. | ||
| */ | ||
| declare class EncryptFile { | ||
| static FIXED_SECRET: string; | ||
| /** | ||
| * Encrypts a plaintext file and saves it to a new location with obfuscation techniques applied. | ||
| * | ||
| * @param {string} inputDecPath - Path to the **plaintext** input file. | ||
| * @param {string} outputEncPath - Path where the **encrypted** file will be saved. | ||
| * @throws {Error} If file operations fail or encryption encounters an error. | ||
| * | ||
| * @example | ||
| * EncryptFile.encryptFile("data.txt", "data.enc"); | ||
| */ | ||
| static encryptFile(inputDecPath: string, outputEncPath: string): void; | ||
| } | ||
| export default EncryptFile; | ||
| //# sourceMappingURL=EncryptFile.d.ts.map |
| {"version":3,"file":"EncryptFile.d.ts","sourceRoot":"","sources":["../src/EncryptFile.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,cAAM,WAAW;IAEb,MAAM,CAAC,YAAY,EAAE,MAAM,CAA8F;IAEzH;;;;;;;;;OASG;IACH,MAAM,CAAC,WAAW,CAAC,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI;CAoCxE;AAED,eAAe,WAAW,CAAC"} |
| "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; | ||
| }; | ||
| })(); | ||
| var __importDefault = (this && this.__importDefault) || function (mod) { | ||
| return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| const fs = __importStar(require("node:fs")); | ||
| const crypto = __importStar(require("node:crypto")); | ||
| const Encryptor_1 = __importDefault(require("./Encryptor")); // Ensure Encryptor is correctly implemented | ||
| /** | ||
| * @class EncryptFile | ||
| * @classdesc Utility class for encrypting files using a combination of random per-file keys and a fixed secret key. | ||
| */ | ||
| class EncryptFile { | ||
| /** | ||
| * Encrypts a plaintext file and saves it to a new location with obfuscation techniques applied. | ||
| * | ||
| * @param {string} inputDecPath - Path to the **plaintext** input file. | ||
| * @param {string} outputEncPath - Path where the **encrypted** file will be saved. | ||
| * @throws {Error} If file operations fail or encryption encounters an error. | ||
| * | ||
| * @example | ||
| * EncryptFile.encryptFile("data.txt", "data.enc"); | ||
| */ | ||
| static encryptFile(inputDecPath, outputEncPath) { | ||
| try { | ||
| // 1️⃣ Read the original file content | ||
| const content = fs.readFileSync(inputDecPath, 'utf-8'); | ||
| // 2️⃣ Generate a random 256-bit key for **this specific file** | ||
| const randomKey = crypto.randomBytes(32).toString('base64'); | ||
| // 3️⃣ Encrypt the generated key using the **fixed secret key** | ||
| const encryptedKey = Encryptor_1.default.encrypt(randomKey, EncryptFile.FIXED_SECRET); | ||
| // 4️⃣ Encrypt the file content using the **randomly generated key** | ||
| const encryptedContent = Encryptor_1.default.encrypt(content, randomKey); | ||
| // 5️⃣ Generate **random obfuscation data** (32 bytes each) | ||
| const randomPrefix = crypto.randomBytes(32).toString('base64'); | ||
| const randomSuffix = crypto.randomBytes(32).toString('base64'); | ||
| // 6️⃣ Construct the obfuscated encrypted file structure | ||
| const formattedContent = `0x3F8AD1B2: ${randomPrefix}\n` + // Random prefix metadata | ||
| `${randomPrefix}\n` + | ||
| `${randomSuffix}\n` + | ||
| "==== START ENCRYPTED DATA ====\n" + | ||
| encryptedKey + "\n" + // Encrypted random key | ||
| encryptedContent + "\n" + // Encrypted file content | ||
| "==== END ENCRYPTED DATA ====\n" + | ||
| `0xFA34F9CD: ${randomSuffix}\n`; // Random suffix metadata | ||
| // 7️⃣ Save the encrypted & obfuscated file | ||
| fs.writeFileSync(outputEncPath, formattedContent, 'utf-8'); | ||
| } | ||
| catch (err) { | ||
| throw new Error(`File encryption failed: ${err instanceof Error ? err.message : "Unknown error"}`); | ||
| } | ||
| } | ||
| } | ||
| EncryptFile.FIXED_SECRET = "mfl+dLeVbxTXFl9B1hb4+0AI4CLYh+LNnP9lMT0d0bcV8Hp0H2rOIsvg9RSPA/9L4V9TWaOJnZYEMyTbrsXKhg=="; | ||
| exports.default = EncryptFile; | ||
| //# sourceMappingURL=EncryptFile.js.map |
| {"version":3,"file":"EncryptFile.js","sourceRoot":"","sources":["../src/EncryptFile.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,4CAA8B;AAC9B,oDAAsC;AACtC,4DAAoC,CAAC,4CAA4C;AAEjF;;;GAGG;AACH,MAAM,WAAW;IAIb;;;;;;;;;OASG;IACH,MAAM,CAAC,WAAW,CAAC,YAAoB,EAAE,aAAqB;QAC1D,IAAI,CAAC;YACD,qCAAqC;YACrC,MAAM,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;YAEvD,+DAA+D;YAC/D,MAAM,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;YAE5D,+DAA+D;YAC/D,MAAM,YAAY,GAAG,mBAAS,CAAC,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;YAE5E,oEAAoE;YACpE,MAAM,gBAAgB,GAAG,mBAAS,CAAC,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;YAE/D,2DAA2D;YAC3D,MAAM,YAAY,GAAG,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;YAC/D,MAAM,YAAY,GAAG,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;YAE/D,wDAAwD;YACxD,MAAM,gBAAgB,GAClB,eAAe,YAAY,IAAI,GAAI,yBAAyB;gBAC5D,GAAG,YAAY,IAAI;gBACnB,GAAG,YAAY,IAAI;gBACnB,kCAAkC;gBAClC,YAAY,GAAG,IAAI,GAAI,uBAAuB;gBAC9C,gBAAgB,GAAG,IAAI,GAAI,yBAAyB;gBACpD,gCAAgC;gBAChC,eAAe,YAAY,IAAI,CAAC,CAAE,yBAAyB;YAE/D,2CAA2C;YAC3C,EAAE,CAAC,aAAa,CAAC,aAAa,EAAE,gBAAgB,EAAE,OAAO,CAAC,CAAC;QAE/D,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CAAC,2BAA2B,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC;QACvG,CAAC;IACL,CAAC;;AA/CM,wBAAY,GAAW,0FAA0F,CAAC;AAkD7H,kBAAe,WAAW,CAAC"} |
| /** | ||
| * @class Encryptor | ||
| * @classdesc Provides AES-GCM encryption with PBKDF2 key derivation for strong security. | ||
| */ | ||
| declare class Encryptor { | ||
| /** | ||
| * Number of iterations for PBKDF2 (increases brute-force resistance). | ||
| * Higher values = **more security** but slower processing. | ||
| */ | ||
| static readonly ITERATIONS: number; | ||
| /** | ||
| * Length of the salt in bytes (16 bytes = 128 bits). | ||
| * Salt ensures **each encryption is unique**, even with the same password. | ||
| */ | ||
| static readonly SALT_LENGTH: number; | ||
| /** | ||
| * AES-256 key length in bytes (32 bytes = 256 bits). | ||
| * AES-256 requires a **32-byte key** for maximum security. | ||
| */ | ||
| static readonly KEY_LENGTH: number; | ||
| /** | ||
| * IV (Initialization Vector) length in bytes (12 bytes = recommended for GCM mode). | ||
| * IV ensures **non-repeating ciphertext** for the same input. | ||
| */ | ||
| static readonly IV_LENGTH: number; | ||
| /** | ||
| * Authentication Tag length in bytes (16 bytes = 128 bits). | ||
| * Ensures the integrity of the ciphertext and prevents tampering. | ||
| */ | ||
| static readonly AUTH_TAG_LENGTH: number; | ||
| /** | ||
| * Encrypts a plaintext string using **AES-256-GCM** with a password-derived key. | ||
| * | ||
| * @param {string} plainText - The text to be encrypted. | ||
| * @param {string} password - The password used to derive the encryption key. | ||
| * @returns {string} - The encrypted text, encoded in Base64 (salt + IV + cipherText + authTag). | ||
| * @throws {Error} - If encryption fails. | ||
| * | ||
| * @example | ||
| * const encrypted = Encryptor.encrypt("Hello, world!", "my_secure_password"); | ||
| * console.log(encrypted); // Encrypted text in Base64 format | ||
| */ | ||
| static encrypt(plainText: string, password: string): string; | ||
| } | ||
| export default Encryptor; | ||
| //# sourceMappingURL=Encryptor.d.ts.map |
| {"version":3,"file":"Encryptor.d.ts","sourceRoot":"","sources":["../src/Encryptor.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,cAAM,SAAS;IACX;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAS;IAE3C;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAM;IAEzC;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAM;IAExC;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAM;IAEvC;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAM;IAE7C;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM;CA+B9D;AAED,eAAe,SAAS,CAAC"} |
| "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 }); | ||
| const crypto = __importStar(require("node:crypto")); | ||
| /** | ||
| * @class Encryptor | ||
| * @classdesc Provides AES-GCM encryption with PBKDF2 key derivation for strong security. | ||
| */ | ||
| class Encryptor { | ||
| /** | ||
| * Encrypts a plaintext string using **AES-256-GCM** with a password-derived key. | ||
| * | ||
| * @param {string} plainText - The text to be encrypted. | ||
| * @param {string} password - The password used to derive the encryption key. | ||
| * @returns {string} - The encrypted text, encoded in Base64 (salt + IV + cipherText + authTag). | ||
| * @throws {Error} - If encryption fails. | ||
| * | ||
| * @example | ||
| * const encrypted = Encryptor.encrypt("Hello, world!", "my_secure_password"); | ||
| * console.log(encrypted); // Encrypted text in Base64 format | ||
| */ | ||
| static encrypt(plainText, password) { | ||
| try { | ||
| // 1️⃣ Generate a **random salt** (unique for every encryption) | ||
| const salt = crypto.randomBytes(this.SALT_LENGTH); | ||
| // 2️⃣ Derive the encryption key using PBKDF2 (SHA-256, 10,000 iterations) | ||
| const key = crypto.pbkdf2Sync(password, salt, this.ITERATIONS, this.KEY_LENGTH, "sha256"); | ||
| // 3️⃣ Generate a **random IV** (essential for AES-GCM security) | ||
| const iv = crypto.randomBytes(this.IV_LENGTH); | ||
| // 4️⃣ Create the AES-GCM cipher | ||
| const cipher = crypto.createCipheriv("aes-256-gcm", key, iv); | ||
| // 5️⃣ Encrypt the plaintext | ||
| let cipherText = cipher.update(plainText, "utf8"); | ||
| cipherText = Buffer.concat([cipherText, cipher.final()]); | ||
| // 6️⃣ Get the **authentication tag** (ensures data integrity) | ||
| const authTag = cipher.getAuthTag(); | ||
| // 7️⃣ Concatenate (salt + IV + cipherText + authTag) into a single buffer | ||
| const encryptedData = Buffer.concat([salt, iv, cipherText, authTag]); | ||
| // 8️⃣ Encode everything as Base64 for easy storage & transmission | ||
| return encryptedData.toString("base64"); | ||
| } | ||
| catch (err) { | ||
| throw new Error(`Encryption failed: ${err instanceof Error ? err.message : "Unknown error"}`); | ||
| } | ||
| } | ||
| } | ||
| /** | ||
| * Number of iterations for PBKDF2 (increases brute-force resistance). | ||
| * Higher values = **more security** but slower processing. | ||
| */ | ||
| Encryptor.ITERATIONS = 10000; | ||
| /** | ||
| * Length of the salt in bytes (16 bytes = 128 bits). | ||
| * Salt ensures **each encryption is unique**, even with the same password. | ||
| */ | ||
| Encryptor.SALT_LENGTH = 16; | ||
| /** | ||
| * AES-256 key length in bytes (32 bytes = 256 bits). | ||
| * AES-256 requires a **32-byte key** for maximum security. | ||
| */ | ||
| Encryptor.KEY_LENGTH = 32; | ||
| /** | ||
| * IV (Initialization Vector) length in bytes (12 bytes = recommended for GCM mode). | ||
| * IV ensures **non-repeating ciphertext** for the same input. | ||
| */ | ||
| Encryptor.IV_LENGTH = 12; | ||
| /** | ||
| * Authentication Tag length in bytes (16 bytes = 128 bits). | ||
| * Ensures the integrity of the ciphertext and prevents tampering. | ||
| */ | ||
| Encryptor.AUTH_TAG_LENGTH = 16; | ||
| exports.default = Encryptor; | ||
| //# sourceMappingURL=Encryptor.js.map |
| {"version":3,"file":"Encryptor.js","sourceRoot":"","sources":["../src/Encryptor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAsC;AAEtC;;;GAGG;AACH,MAAM,SAAS;IA+BX;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,OAAO,CAAC,SAAiB,EAAE,QAAgB;QAC9C,IAAI,CAAC;YACD,+DAA+D;YAC/D,MAAM,IAAI,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAElD,0EAA0E;YAC1E,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;YAE1F,gEAAgE;YAChE,MAAM,EAAE,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAE9C,gCAAgC;YAChC,MAAM,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC,aAAa,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;YAE7D,4BAA4B;YAC5B,IAAI,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;YAClD,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;YAEzD,8DAA8D;YAC9D,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;YAEpC,0EAA0E;YAC1E,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;YAErE,kEAAkE;YAClE,OAAO,aAAa,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAE5C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CAAC,sBAAsB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC;QAClG,CAAC;IACL,CAAC;;AAxED;;;GAGG;AACa,oBAAU,GAAW,KAAK,CAAC;AAE3C;;;GAGG;AACa,qBAAW,GAAW,EAAE,CAAC;AAEzC;;;GAGG;AACa,oBAAU,GAAW,EAAE,CAAC;AAExC;;;GAGG;AACa,mBAAS,GAAW,EAAE,CAAC;AAEvC;;;GAGG;AACa,yBAAe,GAAW,EAAE,CAAC;AA+CjD,kBAAe,SAAS,CAAC"} |
| /** | ||
| * @class HashingUtils | ||
| * @classdesc Provides methods for securely hashing passwords using PBKDF2, salt, and a pepper. | ||
| */ | ||
| declare class HashingUtils { | ||
| private static readonly PEPPER; | ||
| private static readonly ITERATIONS; | ||
| private static readonly SALT_LENGTH; | ||
| private static readonly HASH_LENGTHS; | ||
| /** | ||
| * Generates a secure SHA-512 hash using PBKDF2, a random salt, and a secret pepper. | ||
| * | ||
| * @param {string} input The plain text to hash. | ||
| * @returns {string} The Base64 encoded hash (`salt$hash` format). | ||
| */ | ||
| static generateSecureHashSHA512(input: string): string; | ||
| /** | ||
| * Generates a secure SHA-256 hash using PBKDF2, a random salt, and a secret pepper. | ||
| * | ||
| * @param {string} input The plain text to hash. | ||
| * @returns {string} The Base64 encoded hash (`salt$hash` format). | ||
| */ | ||
| static generateSecureHashSHA256(input: string): string; | ||
| /** | ||
| * Verifies if a SHA-512 hash matches the plain text. | ||
| * | ||
| * @param {string} input The plain text to check. | ||
| * @param {string} storedHash The stored hash (`salt$hash` in Base64). | ||
| * @returns {boolean} `true` if the hash matches, `false` otherwise. | ||
| */ | ||
| static verifyHashSHA512(input: string, storedHash: string): boolean; | ||
| /** | ||
| * Verifies if a SHA-256 hash matches the plain text. | ||
| * | ||
| * @param {string} input The plain text to check. | ||
| * @param {string} storedHash The stored hash (`salt$hash` in Base64). | ||
| * @returns {boolean} `true` if the hash matches, `false` otherwise. | ||
| */ | ||
| static verifyHashSHA256(input: string, storedHash: string): boolean; | ||
| /** | ||
| * Generates a secure hash using PBKDF2 + Salt + Pepper. | ||
| * | ||
| * @param {string} input The plain text to hash. | ||
| * @param {"sha512" | "sha256"} algorithm The hashing algorithm to use. | ||
| * @returns {string} The Base64 encoded hash (`salt$hash` format). | ||
| */ | ||
| private static generateSecureHash; | ||
| /** | ||
| * Verifies if a hash corresponds to the plain text. | ||
| * | ||
| * @param {string} input The plain text to check. | ||
| * @param {string} storedHash The stored hash (`salt$hash` in Base64). | ||
| * @param {"sha512" | "sha256"} algorithm The hashing algorithm used. | ||
| * @returns {boolean} `true` if the hash matches, `false` otherwise. | ||
| */ | ||
| private static verifyHash; | ||
| /** | ||
| * Derives a key using PBKDF2 + Pepper. | ||
| * | ||
| * @param {string} input The plain text. | ||
| * @param {Buffer} salt The salt used in hashing. | ||
| * @param {"sha512" | "sha256"} algorithm The hashing algorithm used. | ||
| * @returns {Buffer} The derived hash. | ||
| */ | ||
| private static deriveKey; | ||
| /** | ||
| * Generates a random salt. | ||
| * | ||
| * @returns {Buffer} The random salt. | ||
| */ | ||
| private static generateSalt; | ||
| } | ||
| export default HashingUtils; | ||
| //# sourceMappingURL=HashingUtils.d.ts.map |
| {"version":3,"file":"HashingUtils.d.ts","sourceRoot":"","sources":["../src/HashingUtils.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,cAAM,YAAY;IACd,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAqD;IAEnF,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAiB;IAEnD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAc;IAEjD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAGlC;IAEF;;;;;OAKG;IACH,MAAM,CAAC,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAItD;;;;;OAKG;IACH,MAAM,CAAC,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAItD;;;;;;OAMG;IACH,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO;IAInE;;;;;;OAMG;IACH,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO;IAInE;;;;;;OAMG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAUjC;;;;;;;OAOG;IACH,OAAO,CAAC,MAAM,CAAC,UAAU;IAczB;;;;;;;OAOG;IACH,OAAO,CAAC,MAAM,CAAC,SAAS;IASxB;;;;OAIG;IACH,OAAO,CAAC,MAAM,CAAC,YAAY;CAG9B;AAED,eAAe,YAAY,CAAC"} |
| "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 }); | ||
| const crypto = __importStar(require("crypto")); | ||
| /** | ||
| * @class HashingUtils | ||
| * @classdesc Provides methods for securely hashing passwords using PBKDF2, salt, and a pepper. | ||
| */ | ||
| class HashingUtils { | ||
| /** | ||
| * Generates a secure SHA-512 hash using PBKDF2, a random salt, and a secret pepper. | ||
| * | ||
| * @param {string} input The plain text to hash. | ||
| * @returns {string} The Base64 encoded hash (`salt$hash` format). | ||
| */ | ||
| static generateSecureHashSHA512(input) { | ||
| return this.generateSecureHash(input, "sha512"); | ||
| } | ||
| /** | ||
| * Generates a secure SHA-256 hash using PBKDF2, a random salt, and a secret pepper. | ||
| * | ||
| * @param {string} input The plain text to hash. | ||
| * @returns {string} The Base64 encoded hash (`salt$hash` format). | ||
| */ | ||
| static generateSecureHashSHA256(input) { | ||
| return this.generateSecureHash(input, "sha256"); | ||
| } | ||
| /** | ||
| * Verifies if a SHA-512 hash matches the plain text. | ||
| * | ||
| * @param {string} input The plain text to check. | ||
| * @param {string} storedHash The stored hash (`salt$hash` in Base64). | ||
| * @returns {boolean} `true` if the hash matches, `false` otherwise. | ||
| */ | ||
| static verifyHashSHA512(input, storedHash) { | ||
| return this.verifyHash(input, storedHash, "sha512"); | ||
| } | ||
| /** | ||
| * Verifies if a SHA-256 hash matches the plain text. | ||
| * | ||
| * @param {string} input The plain text to check. | ||
| * @param {string} storedHash The stored hash (`salt$hash` in Base64). | ||
| * @returns {boolean} `true` if the hash matches, `false` otherwise. | ||
| */ | ||
| static verifyHashSHA256(input, storedHash) { | ||
| return this.verifyHash(input, storedHash, "sha256"); | ||
| } | ||
| /** | ||
| * Generates a secure hash using PBKDF2 + Salt + Pepper. | ||
| * | ||
| * @param {string} input The plain text to hash. | ||
| * @param {"sha512" | "sha256"} algorithm The hashing algorithm to use. | ||
| * @returns {string} The Base64 encoded hash (`salt$hash` format). | ||
| */ | ||
| static generateSecureHash(input, algorithm) { | ||
| try { | ||
| const salt = this.generateSalt(); | ||
| const hash = this.deriveKey(input, salt, algorithm); | ||
| return `${salt.toString("base64")}$${hash.toString("base64")}`; | ||
| } | ||
| catch (error) { | ||
| throw new Error(`Error generating hash (${algorithm}): ${error instanceof Error ? error.message : error}`); | ||
| } | ||
| } | ||
| /** | ||
| * Verifies if a hash corresponds to the plain text. | ||
| * | ||
| * @param {string} input The plain text to check. | ||
| * @param {string} storedHash The stored hash (`salt$hash` in Base64). | ||
| * @param {"sha512" | "sha256"} algorithm The hashing algorithm used. | ||
| * @returns {boolean} `true` if the hash matches, `false` otherwise. | ||
| */ | ||
| static verifyHash(input, storedHash, algorithm) { | ||
| try { | ||
| const [storedSaltBase64, storedHashBase64] = storedHash.split("$"); | ||
| const storedSalt = Buffer.from(storedSaltBase64, "base64"); | ||
| const storedHashBuffer = Buffer.from(storedHashBase64, "base64"); | ||
| const computedHash = this.deriveKey(input, storedSalt, algorithm); | ||
| return crypto.timingSafeEqual(storedHashBuffer, computedHash); | ||
| } | ||
| catch (_a) { | ||
| return false; // Return false if an error occurs. | ||
| } | ||
| } | ||
| /** | ||
| * Derives a key using PBKDF2 + Pepper. | ||
| * | ||
| * @param {string} input The plain text. | ||
| * @param {Buffer} salt The salt used in hashing. | ||
| * @param {"sha512" | "sha256"} algorithm The hashing algorithm used. | ||
| * @returns {Buffer} The derived hash. | ||
| */ | ||
| static deriveKey(input, salt, algorithm) { | ||
| const hashLength = this.HASH_LENGTHS[algorithm]; | ||
| // Add pepper before hashing | ||
| const pepperedInput = Buffer.concat([Buffer.from(input, "utf8"), this.PEPPER]); | ||
| return crypto.pbkdf2Sync(pepperedInput, salt, this.ITERATIONS, hashLength, algorithm); | ||
| } | ||
| /** | ||
| * Generates a random salt. | ||
| * | ||
| * @returns {Buffer} The random salt. | ||
| */ | ||
| static generateSalt() { | ||
| return crypto.randomBytes(this.SALT_LENGTH); | ||
| } | ||
| } | ||
| HashingUtils.PEPPER = Buffer.from("SuperSecretPepperKey12345!"); | ||
| HashingUtils.ITERATIONS = 10000; // PBKDF2 iterations for stronger security | ||
| HashingUtils.SALT_LENGTH = 64; // Salt length (64 bytes = 512 bits) | ||
| HashingUtils.HASH_LENGTHS = { | ||
| sha512: 64, // 512 bits (64 bytes) | ||
| sha256: 32, // 256 bits (32 bytes) | ||
| }; | ||
| exports.default = HashingUtils; | ||
| //# sourceMappingURL=HashingUtils.js.map |
| {"version":3,"file":"HashingUtils.js","sourceRoot":"","sources":["../src/HashingUtils.ts"],"names":[],"mappings":"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"} |
| /** | ||
| * @class KeyGenerator | ||
| * @classdesc Class for generating secure keys and random passwords using strong cryptography. | ||
| */ | ||
| declare class KeyGenerator { | ||
| private static readonly SALT_LENGTH; | ||
| private static readonly ITERATIONS; | ||
| private static readonly KEY_LENGTH; | ||
| /** | ||
| * Generates a secure AES key from a password and salt using PBKDF2 with HMAC-SHA-512. | ||
| * | ||
| * @param {string} password The password used to generate the key. | ||
| * @param {Buffer} salt The random salt used in the key derivation. | ||
| * @returns {Promise<Buffer>} A secure 256-bit (32-byte) derived key. | ||
| * @throws {Error} If an error occurs during the key generation. | ||
| */ | ||
| static generateKey(password: string, salt: Buffer): Promise<Buffer>; | ||
| /** | ||
| * Generates a random salt of fixed length. | ||
| * | ||
| * @returns {Buffer} A random 16-byte salt buffer. | ||
| */ | ||
| static generateSalt(): Buffer; | ||
| /** | ||
| * Generates a secure random password containing alphanumeric characters and special symbols. | ||
| * | ||
| * @param {number} length The length of the generated password (minimum 1). | ||
| * @returns {string} A securely generated random password. | ||
| * @throws {Error} If the length is less than or equal to 0. | ||
| */ | ||
| static generateSecurePassword(length: number): string; | ||
| } | ||
| export default KeyGenerator; | ||
| //# sourceMappingURL=KeyGenerator.d.ts.map |
| {"version":3,"file":"KeyGenerator.d.ts","sourceRoot":"","sources":["../src/KeyGenerator.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,cAAM,YAAY;IACd,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAc;IACjD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAiB;IACnD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAc;IAEhD;;;;;;;OAOG;WACU,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IASzE;;;;OAIG;IACH,MAAM,CAAC,YAAY,IAAI,MAAM;IAI7B;;;;;;OAMG;IACH,MAAM,CAAC,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;CASxD;AAED,eAAe,YAAY,CAAC"} |
| "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; | ||
| }; | ||
| })(); | ||
| var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
| function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
| return new (P || (P = Promise))(function (resolve, reject) { | ||
| function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
| function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
| function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
| step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
| }); | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| const crypto = __importStar(require("crypto")); | ||
| /** | ||
| * @class KeyGenerator | ||
| * @classdesc Class for generating secure keys and random passwords using strong cryptography. | ||
| */ | ||
| class KeyGenerator { | ||
| /** | ||
| * Generates a secure AES key from a password and salt using PBKDF2 with HMAC-SHA-512. | ||
| * | ||
| * @param {string} password The password used to generate the key. | ||
| * @param {Buffer} salt The random salt used in the key derivation. | ||
| * @returns {Promise<Buffer>} A secure 256-bit (32-byte) derived key. | ||
| * @throws {Error} If an error occurs during the key generation. | ||
| */ | ||
| static generateKey(password, salt) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| return new Promise((resolve, reject) => { | ||
| crypto.pbkdf2(password, salt, this.ITERATIONS, this.KEY_LENGTH, "sha512", (err, derivedKey) => { | ||
| if (err) | ||
| return reject(new Error(`Error generating key: ${err.message}`)); | ||
| resolve(derivedKey); | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| /** | ||
| * Generates a random salt of fixed length. | ||
| * | ||
| * @returns {Buffer} A random 16-byte salt buffer. | ||
| */ | ||
| static generateSalt() { | ||
| return crypto.randomBytes(this.SALT_LENGTH); | ||
| } | ||
| /** | ||
| * Generates a secure random password containing alphanumeric characters and special symbols. | ||
| * | ||
| * @param {number} length The length of the generated password (minimum 1). | ||
| * @returns {string} A securely generated random password. | ||
| * @throws {Error} If the length is less than or equal to 0. | ||
| */ | ||
| static generateSecurePassword(length) { | ||
| if (length <= 0) { | ||
| throw new Error("Password length must be greater than 0."); | ||
| } | ||
| const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+"; | ||
| const randomBytes = crypto.randomBytes(length); | ||
| return Array.from(randomBytes, byte => characters[byte % characters.length]).join(""); | ||
| } | ||
| } | ||
| KeyGenerator.SALT_LENGTH = 16; // Recommended salt length (16 bytes) | ||
| KeyGenerator.ITERATIONS = 20000; // Recommended iterations for PBKDF2 for enhanced security | ||
| KeyGenerator.KEY_LENGTH = 32; // Key length (256 bits = 32 bytes, ideal for AES) | ||
| exports.default = KeyGenerator; | ||
| //# sourceMappingURL=KeyGenerator.js.map |
| {"version":3,"file":"KeyGenerator.js","sourceRoot":"","sources":["../src/KeyGenerator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAiC;AAEjC;;;GAGG;AACH,MAAM,YAAY;IAKd;;;;;;;OAOG;IACH,MAAM,CAAO,WAAW,CAAC,QAAgB,EAAE,IAAY;;YACnD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACnC,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,EAAE;oBAC1F,IAAI,GAAG;wBAAE,OAAO,MAAM,CAAC,IAAI,KAAK,CAAC,yBAAyB,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;oBAC1E,OAAO,CAAC,UAAU,CAAC,CAAC;gBACxB,CAAC,CAAC,CAAC;YACP,CAAC,CAAC,CAAC;QACP,CAAC;KAAA;IAED;;;;OAIG;IACH,MAAM,CAAC,YAAY;QACf,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAChD,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,sBAAsB,CAAC,MAAc;QACxC,IAAI,MAAM,IAAI,CAAC,EAAE,CAAC;YACd,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;QAC/D,CAAC;QAED,MAAM,UAAU,GAAG,8EAA8E,CAAC;QAClG,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAC/C,OAAO,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC1F,CAAC;;AA7CuB,wBAAW,GAAW,EAAE,CAAC,CAAC,qCAAqC;AAC/D,uBAAU,GAAW,KAAK,CAAC,CAAC,0DAA0D;AACtF,uBAAU,GAAW,EAAE,CAAC,CAAC,kDAAkD;AA8CvG,kBAAe,YAAY,CAAC"} |
| /** | ||
| * @class SecureKeys | ||
| * @classdesc Class for managing secure key storage, decryption, and retrieval. | ||
| * This class supports loading encrypted data, decrypting it, and storing it in memory for fast access. | ||
| */ | ||
| declare class SecureKeys { | ||
| private static readonly FIXED_SECRET; | ||
| private static decryptedContent; | ||
| private static keyValueMap; | ||
| /** | ||
| * Initializes the class by loading and decrypting the content of an encrypted file. | ||
| * | ||
| * @param {string} encFilePath The path to the encrypted .enc file. | ||
| * @returns {Promise<void>} Resolves when the file is loaded and decrypted successfully. | ||
| * @throws {Error} If an error occurs during file reading or decryption. | ||
| */ | ||
| static init(encFilePath: string): Promise<void>; | ||
| /** | ||
| * Parses the decrypted content and stores it in a key-value map. | ||
| * Only processes lines that match the format: "| key -> value". | ||
| */ | ||
| private static parseDecryptedContent; | ||
| /** | ||
| * Decrypts a given encrypted text using AES-GCM with a key derived from PBKDF2. | ||
| * | ||
| * @param {string} encryptedText The encrypted text in Base64. | ||
| * @param {string} password The password used to derive the decryption key. | ||
| * @returns {string | undefined} The decrypted text or undefined if an error occurs. | ||
| * @throws {Error} If decryption fails. | ||
| */ | ||
| private static decrypt; | ||
| /** | ||
| * Retrieves the value associated with a key from the in-memory key-value map. | ||
| * | ||
| * @param {string} keyName The name of the key to retrieve. | ||
| * @returns {any} The associated value, or null if the key does not exist. | ||
| */ | ||
| static getKey(keyName: string): any | null; | ||
| /** | ||
| * Extracts the encrypted key from the encrypted file content. | ||
| * | ||
| * @param {string} content The content of the encrypted file. | ||
| * @returns {string | null} The encrypted key in Base64 format, or null if not found. | ||
| */ | ||
| private static extractEncryptedKey; | ||
| /** | ||
| * Extracts the encrypted data from the encrypted file content. | ||
| * | ||
| * @param {string} content The content of the encrypted file. | ||
| * @returns {string | null} The encrypted data in Base64 format, or null if not found. | ||
| */ | ||
| private static extractEncryptedData; | ||
| } | ||
| export default SecureKeys; | ||
| //# sourceMappingURL=SecureKeys.d.ts.map |
| {"version":3,"file":"SecureKeys.d.ts","sourceRoot":"","sources":["../src/SecureKeys.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,cAAM,UAAU;IACZ,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAsG;IAC1I,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAqB;IACpD,OAAO,CAAC,MAAM,CAAC,WAAW,CAA8B;IAExD;;;;;;OAMG;WACU,IAAI,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoBrD;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,qBAAqB;IAgBpC;;;;;;;OAOG;IACH,OAAO,CAAC,MAAM,CAAC,OAAO;IA8BtB;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,GAAG,GAAG,IAAI;IAI1C;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,mBAAmB;IAUlC;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,oBAAoB;CAatC;AAED,eAAe,UAAU,CAAC"} |
| "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; | ||
| }; | ||
| })(); | ||
| var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
| function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
| return new (P || (P = Promise))(function (resolve, reject) { | ||
| function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
| function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
| function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
| step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
| }); | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| const fs = __importStar(require("node:fs")); | ||
| const crypto = __importStar(require("node:crypto")); | ||
| /** | ||
| * @class SecureKeys | ||
| * @classdesc Class for managing secure key storage, decryption, and retrieval. | ||
| * This class supports loading encrypted data, decrypting it, and storing it in memory for fast access. | ||
| */ | ||
| class SecureKeys { | ||
| /** | ||
| * Initializes the class by loading and decrypting the content of an encrypted file. | ||
| * | ||
| * @param {string} encFilePath The path to the encrypted .enc file. | ||
| * @returns {Promise<void>} Resolves when the file is loaded and decrypted successfully. | ||
| * @throws {Error} If an error occurs during file reading or decryption. | ||
| */ | ||
| static init(encFilePath) { | ||
| return __awaiter(this, void 0, void 0, function* () { | ||
| const encryptedFileContent = fs.readFileSync(encFilePath, { encoding: 'utf8' }); | ||
| // Extract and decrypt key and data | ||
| const encryptedKey = this.extractEncryptedKey(encryptedFileContent); | ||
| const encryptedData = this.extractEncryptedData(encryptedFileContent); | ||
| if (!encryptedKey || !encryptedData) { | ||
| throw new Error("Encrypted key or data not found in the file."); | ||
| } | ||
| const encryptionKey = this.decrypt(encryptedKey, this.FIXED_SECRET); | ||
| if (!encryptionKey) | ||
| throw new Error("Failed to decrypt the encryption key."); | ||
| this.decryptedContent = this.decrypt(encryptedData, encryptionKey); | ||
| // Parse decrypted content into a key-value map for fast access | ||
| this.parseDecryptedContent(); | ||
| }); | ||
| } | ||
| /** | ||
| * Parses the decrypted content and stores it in a key-value map. | ||
| * Only processes lines that match the format: "| key -> value". | ||
| */ | ||
| static parseDecryptedContent() { | ||
| this.keyValueMap = {}; // Clear previous content | ||
| if (!this.decryptedContent) | ||
| return; | ||
| this.decryptedContent.split("\n").forEach(line => { | ||
| if (line.startsWith("| ") && line.includes("->")) { | ||
| const parts = line.split("->"); | ||
| if (parts.length === 2) { | ||
| const key = parts[0].replace("|", "").trim(); | ||
| const value = parts[1].trim(); | ||
| this.keyValueMap[key] = value; | ||
| } | ||
| } | ||
| }); | ||
| } | ||
| /** | ||
| * Decrypts a given encrypted text using AES-GCM with a key derived from PBKDF2. | ||
| * | ||
| * @param {string} encryptedText The encrypted text in Base64. | ||
| * @param {string} password The password used to derive the decryption key. | ||
| * @returns {string | undefined} The decrypted text or undefined if an error occurs. | ||
| * @throws {Error} If decryption fails. | ||
| */ | ||
| static decrypt(encryptedText, password) { | ||
| try { | ||
| // Convert encrypted text from Base64 to Buffer | ||
| const encryptedData = Buffer.from(encryptedText, 'base64'); | ||
| // Extract salt, IV, cipher text, and auth tag | ||
| const salt = encryptedData.slice(0, 16); | ||
| const iv = encryptedData.slice(16, 28); | ||
| const cipherText = encryptedData.slice(28, encryptedData.length - 16); | ||
| const authTag = encryptedData.slice(encryptedData.length - 16); | ||
| // Derive the key using PBKDF2 | ||
| const key = crypto.pbkdf2Sync(password, salt, 10000, 32, 'sha256'); | ||
| // Create AES-GCM decipher | ||
| const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); | ||
| decipher.setAuthTag(authTag); | ||
| // Decrypt the text | ||
| let decryptedText = decipher.update(cipherText); | ||
| decryptedText = Buffer.concat([decryptedText, decipher.final()]); | ||
| return decryptedText.toString('utf8'); | ||
| } | ||
| catch (error) { | ||
| if (error instanceof Error) { | ||
| throw new Error("Decryption error: " + error.message); | ||
| } | ||
| } | ||
| } | ||
| /** | ||
| * Retrieves the value associated with a key from the in-memory key-value map. | ||
| * | ||
| * @param {string} keyName The name of the key to retrieve. | ||
| * @returns {any} The associated value, or null if the key does not exist. | ||
| */ | ||
| static getKey(keyName) { | ||
| return this.keyValueMap[keyName] || null; | ||
| } | ||
| /** | ||
| * Extracts the encrypted key from the encrypted file content. | ||
| * | ||
| * @param {string} content The content of the encrypted file. | ||
| * @returns {string | null} The encrypted key in Base64 format, or null if not found. | ||
| */ | ||
| static extractEncryptedKey(content) { | ||
| const startIndex = content.indexOf("==== START ENCRYPTED DATA ===="); | ||
| if (startIndex === -1) | ||
| return null; | ||
| const endIndex = content.indexOf("\n", startIndex + "==== START ENCRYPTED DATA ====\n".length); | ||
| if (endIndex === -1) | ||
| return null; | ||
| return content.substring(startIndex + "==== START ENCRYPTED DATA ====\n".length, endIndex).trim(); | ||
| } | ||
| /** | ||
| * Extracts the encrypted data from the encrypted file content. | ||
| * | ||
| * @param {string} content The content of the encrypted file. | ||
| * @returns {string | null} The encrypted data in Base64 format, or null if not found. | ||
| */ | ||
| static extractEncryptedData(content) { | ||
| const startIndex = content.indexOf("==== START ENCRYPTED DATA ===="); | ||
| if (startIndex === -1) | ||
| return null; | ||
| const firstLineEnd = content.indexOf("\n", startIndex + "==== START ENCRYPTED DATA ====\n".length); | ||
| if (firstLineEnd === -1) | ||
| return null; | ||
| const dataStart = firstLineEnd + 1; | ||
| const endIndex = content.indexOf("==== END ENCRYPTED DATA ====", dataStart); | ||
| if (endIndex === -1) | ||
| return null; | ||
| return content.substring(dataStart, endIndex).trim(); | ||
| } | ||
| } | ||
| SecureKeys.FIXED_SECRET = "mfl+dLeVbxTXFl9B1hb4+0AI4CLYh+LNnP9lMT0d0bcV8Hp0H2rOIsvg9RSPA/9L4V9TWaOJnZYEMyTbrsXKhg=="; | ||
| SecureKeys.keyValueMap = {}; // In-memory key-value store | ||
| exports.default = SecureKeys; | ||
| //# sourceMappingURL=SecureKeys.js.map |
| {"version":3,"file":"SecureKeys.js","sourceRoot":"","sources":["../src/SecureKeys.ts"],"names":[],"mappings":"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"} |
| /** | ||
| * @class SecurityUtils | ||
| * @classdesc This class provides advanced security utilities, including HMAC generation and verification, | ||
| * secure key generation using PBKDF2, random key and salt generation, and more. | ||
| */ | ||
| declare class SecurityUtils { | ||
| private static readonly HMAC_ALGORITHM; | ||
| private static readonly PBKDF2_ITERATIONS; | ||
| private static readonly KEY_LENGTH; | ||
| /** | ||
| * Generates an HMAC (Hashed Message Authentication Code) using SHA-512 with a secret key. | ||
| * | ||
| * @param {string} message The message to authenticate. | ||
| * @param {string} secretKey The secret key used to generate the HMAC. | ||
| * @returns {string | undefined} The generated HMAC in Base64 format, or undefined if an error occurs. | ||
| * @throws {Error} If there is an error during HMAC generation. | ||
| */ | ||
| static generateHMAC(message: string, secretKey: string): string | undefined; | ||
| /** | ||
| * Verifies if a given HMAC is valid by comparing it with the computed HMAC for the message. | ||
| * | ||
| * @param {string} message The original message. | ||
| * @param {string} secretKey The secret key used to generate the HMAC. | ||
| * @param {string} receivedHMAC The received HMAC to verify. | ||
| * @returns {boolean} Returns true if the HMAC is valid, false otherwise. | ||
| */ | ||
| static verifyHMAC(message: string, secretKey: string, receivedHMAC: string): boolean; | ||
| /** | ||
| * Generates a secure secret key using PBKDF2 with HMAC-SHA-512. | ||
| * | ||
| * @param {string} password The base password to derive the key. | ||
| * @param {Buffer} salt A random value to strengthen the key. | ||
| * @returns {string | undefined} A secure secret key in Base64 format, or undefined if an error occurs. | ||
| * @throws {Error} If there is an error during key generation. | ||
| */ | ||
| static generateSecureKey(password: string, salt: Buffer): string | undefined; | ||
| /** | ||
| * Generates a secure random secret key. | ||
| * | ||
| * @returns {string} A random secret key in Base64 format. | ||
| */ | ||
| static generateRandomKey(): string; | ||
| /** | ||
| * Generates a secure random salt. | ||
| * | ||
| * @returns {Buffer} A random salt in bytes (256 bits). | ||
| */ | ||
| static generateSalt(): Buffer; | ||
| } | ||
| export default SecurityUtils; | ||
| //# sourceMappingURL=SecurityUtils.d.ts.map |
| {"version":3,"file":"SecurityUtils.d.ts","sourceRoot":"","sources":["../src/SecurityUtils.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,cAAM,aAAa;IAEf,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAoB;IAC1D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAkB;IAC3D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAc;IAEhD;;;;;;;OAOG;IACH,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAgB3E;;;;;;;OAOG;IACH,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO;IAKpF;;;;;;;OAOG;IACH,MAAM,CAAC,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAY5E;;;;OAIG;IACH,MAAM,CAAC,iBAAiB,IAAI,MAAM;IAKlC;;;;OAIG;IACH,MAAM,CAAC,YAAY,IAAI,MAAM;CAGhC;AAED,eAAe,aAAa,CAAC"} |
| "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 }); | ||
| const crypto = __importStar(require("crypto")); | ||
| /** | ||
| * @class SecurityUtils | ||
| * @classdesc This class provides advanced security utilities, including HMAC generation and verification, | ||
| * secure key generation using PBKDF2, random key and salt generation, and more. | ||
| */ | ||
| class SecurityUtils { | ||
| /** | ||
| * Generates an HMAC (Hashed Message Authentication Code) using SHA-512 with a secret key. | ||
| * | ||
| * @param {string} message The message to authenticate. | ||
| * @param {string} secretKey The secret key used to generate the HMAC. | ||
| * @returns {string | undefined} The generated HMAC in Base64 format, or undefined if an error occurs. | ||
| * @throws {Error} If there is an error during HMAC generation. | ||
| */ | ||
| static generateHMAC(message, secretKey) { | ||
| try { | ||
| // Create an HMAC instance using the SHA-512 algorithm | ||
| const hmac = crypto.createHmac(this.HMAC_ALGORITHM, secretKey); | ||
| // Generate the HMAC for the message | ||
| hmac.update(message); | ||
| const hmacBytes = hmac.digest(); | ||
| // Return the HMAC encoded in Base64 | ||
| return hmacBytes.toString('base64'); | ||
| } | ||
| catch (error) { | ||
| if (error instanceof Error) | ||
| throw new Error('Error generating HMAC: ' + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Verifies if a given HMAC is valid by comparing it with the computed HMAC for the message. | ||
| * | ||
| * @param {string} message The original message. | ||
| * @param {string} secretKey The secret key used to generate the HMAC. | ||
| * @param {string} receivedHMAC The received HMAC to verify. | ||
| * @returns {boolean} Returns true if the HMAC is valid, false otherwise. | ||
| */ | ||
| static verifyHMAC(message, secretKey, receivedHMAC) { | ||
| const computedHMAC = this.generateHMAC(message, secretKey); | ||
| return computedHMAC === receivedHMAC; | ||
| } | ||
| /** | ||
| * Generates a secure secret key using PBKDF2 with HMAC-SHA-512. | ||
| * | ||
| * @param {string} password The base password to derive the key. | ||
| * @param {Buffer} salt A random value to strengthen the key. | ||
| * @returns {string | undefined} A secure secret key in Base64 format, or undefined if an error occurs. | ||
| * @throws {Error} If there is an error during key generation. | ||
| */ | ||
| static generateSecureKey(password, salt) { | ||
| try { | ||
| // Derive the key using PBKDF2 with SHA-512 | ||
| const key = crypto.pbkdf2Sync(password, salt, this.PBKDF2_ITERATIONS, this.KEY_LENGTH, 'sha512'); | ||
| // Return the derived key encoded in Base64 | ||
| return key.toString('base64'); | ||
| } | ||
| catch (error) { | ||
| if (error instanceof Error) | ||
| throw new Error('Error generating secure key: ' + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Generates a secure random secret key. | ||
| * | ||
| * @returns {string} A random secret key in Base64 format. | ||
| */ | ||
| static generateRandomKey() { | ||
| const key = crypto.randomBytes(64); // 512 bits (64 bytes) | ||
| return key.toString('base64'); | ||
| } | ||
| /** | ||
| * Generates a secure random salt. | ||
| * | ||
| * @returns {Buffer} A random salt in bytes (256 bits). | ||
| */ | ||
| static generateSalt() { | ||
| return crypto.randomBytes(32); // 256 bits | ||
| } | ||
| } | ||
| SecurityUtils.HMAC_ALGORITHM = 'sha512'; // HMAC algorithm (SHA-512) | ||
| SecurityUtils.PBKDF2_ITERATIONS = 150000; // PBKDF2 iterations for key derivation | ||
| SecurityUtils.KEY_LENGTH = 64; // 512 bits for a more secure key length | ||
| exports.default = SecurityUtils; | ||
| //# sourceMappingURL=SecurityUtils.js.map |
| {"version":3,"file":"SecurityUtils.js","sourceRoot":"","sources":["../src/SecurityUtils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAiC;AAEjC;;;;GAIG;AACH,MAAM,aAAa;IAMf;;;;;;;OAOG;IACH,MAAM,CAAC,YAAY,CAAC,OAAe,EAAE,SAAiB;QAClD,IAAI,CAAC;YACD,sDAAsD;YACtD,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC;YAE/D,oCAAoC;YACpC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YACrB,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;YAEhC,oCAAoC;YACpC,OAAO,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACxC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,KAAK;gBAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;QAC3F,CAAC;IACL,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,UAAU,CAAC,OAAe,EAAE,SAAiB,EAAE,YAAoB;QACtE,MAAM,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAC3D,OAAO,YAAY,KAAK,YAAY,CAAC;IACzC,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,iBAAiB,CAAC,QAAgB,EAAE,IAAY;QACnD,IAAI,CAAC;YACD,2CAA2C;YAC3C,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,iBAAiB,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;YAEjG,2CAA2C;YAC3C,OAAO,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAClC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,KAAK;gBAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;QACjG,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,iBAAiB;QACpB,MAAM,GAAG,GAAG,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,sBAAsB;QAC1D,OAAO,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAClC,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,YAAY;QACf,OAAO,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW;IAC9C,CAAC;;AA9EuB,4BAAc,GAAW,QAAQ,CAAC,CAAC,2BAA2B;AAC9D,+BAAiB,GAAW,MAAM,CAAC,CAAC,uCAAuC;AAC3E,wBAAU,GAAW,EAAE,CAAC,CAAC,wCAAwC;AA+E7F,kBAAe,aAAa,CAAC"} |
| { | ||
| "compilerOptions": { | ||
| "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ | ||
| "module": "commonjs", /* Specify what module code is generated. */ | ||
| "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ | ||
| "declarationMap": true, /* Create sourcemaps for d.ts files. */ | ||
| "sourceMap": true, /* Create source map files for emitted JavaScript files. */ | ||
| "removeComments": false, /* Disable emitting comments. */ | ||
| "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ | ||
| "strict": true, /* Enable all strict type-checking options. */ | ||
| "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ | ||
| "skipLibCheck": true, /* Skip type checking all .d.ts files. */ | ||
| "esModuleInterop": true, | ||
| "allowSyntheticDefaultImports": true, | ||
| "outDir": "./build", | ||
| "rootDir": "./src", | ||
| } | ||
| } |
+20
-5
| { | ||
| "name": "cryptix", | ||
| "version": "1.0.0", | ||
| "main": "src/cryptix.js", | ||
| "keywords": [], | ||
| "version": "1.0.1", | ||
| "main": "build/cryptix.js", | ||
| "scripts": { | ||
| "build": "tsc", | ||
| "docs": "npx jsdoc2md build/**/*.js > README.md", | ||
| "test": "echo \"No tests specified\" && exit 0" | ||
| }, | ||
| "keywords": [ | ||
| "encryption", | ||
| "decryption", | ||
| "crypto", | ||
| "security", | ||
| "library" | ||
| ], | ||
| "author": "Jesus Daniel", | ||
| "license": "GPL-3.0", | ||
| "description": "Libreria para encriptar y desencriptar datos", | ||
| "description": "A lightweight library for encrypting and decrypting data with strong cryptographic algorithms.", | ||
| "devDependencies": { | ||
| "@types/node": "^22.13.2", | ||
| "jsdoc": "^4.0.4", | ||
| "jsdoc-to-markdown": "^9.1.1" | ||
| }, | ||
| "engines": { | ||
| "node": ">=22.13.1" | ||
| } | ||
| } | ||
| } |
+413
-235
@@ -5,54 +5,35 @@ ## Classes | ||
| <dt><a href="#AsimetricUtils">AsimetricUtils</a></dt> | ||
| <dd><p>La clase AsimetricUtils proporciona métodos para trabajar con encriptación y desencriptación | ||
| usando criptografía asimétrica, específicamente con el algoritmo RSA. Incluye funcionalidades | ||
| para generar pares de claves (pública y privada), guardar y cargar claves desde archivos, | ||
| y encriptar/desencriptar datos.</p> | ||
| <dd><p>A utility class for asymmetric encryption using RSA. | ||
| Provides functions for generating, storing, retrieving, encrypting, and decrypting data securely.</p> | ||
| </dd> | ||
| <dt><a href="#Decryptor">Decryptor</a></dt> | ||
| <dd><p>Utility class for decrypting AES-GCM encrypted data using a password-derived key.</p> | ||
| </dd> | ||
| <dt><a href="#EncryptFile">EncryptFile</a></dt> | ||
| <dd><p>Clase encargada de cifrar archivos utilizando una clave secreta fija y una clave aleatoria generada | ||
| dinámicamente para cada archivo. Aplica técnicas de ofuscación para aumentar la seguridad.</p> | ||
| <dd><p>Utility class for encrypting files using a combination of random per-file keys and a fixed secret key.</p> | ||
| </dd> | ||
| <dt><a href="#Encryptor">Encryptor</a></dt> | ||
| <dd><p>Provides AES-GCM encryption with PBKDF2 key derivation for strong security.</p> | ||
| </dd> | ||
| <dt><a href="#HashingUtils">HashingUtils</a></dt> | ||
| <dd><p>Clase segura para hashing con PBKDF2, SHA-512, SHA-256, salt aleatorio y un pepper secreto.</p> | ||
| <dd><p>Provides methods for securely hashing passwords using PBKDF2, salt, and a pepper.</p> | ||
| </dd> | ||
| <dt><a href="#KeyGenerator">KeyGenerator</a></dt> | ||
| <dd><p>Clase KeyGenerator que proporciona métodos para generar claves seguras | ||
| a partir de contraseñas y sal (salt), utilizando algoritmos criptográficos robustos.</p> | ||
| <dd><p>Class for generating secure keys and random passwords using strong cryptography.</p> | ||
| </dd> | ||
| <dt><a href="#SecureKeys">SecureKeys</a></dt> | ||
| <dd><p>Class for managing secure key storage, decryption, and retrieval. | ||
| This class supports loading encrypted data, decrypting it, and storing it in memory for fast access.</p> | ||
| </dd> | ||
| <dt><a href="#SecurityUtils">SecurityUtils</a></dt> | ||
| <dd><p>Clase SecurityUtils con funciones avanzadas de seguridad, | ||
| incluyendo generación y verificación de HMAC con SHA-512, claves seguras y más.</p> | ||
| <dd><p>This class provides advanced security utilities, including HMAC generation and verification, | ||
| secure key generation using PBKDF2, random key and salt generation, and more.</p> | ||
| </dd> | ||
| </dl> | ||
| ## Functions | ||
| <dl> | ||
| <dt><a href="#init">init(encFilePath)</a></dt> | ||
| <dd><p>Inicializa la clase cargando y desencriptando el contenido del archivo cifrado.</p> | ||
| </dd> | ||
| <dt><a href="#parseDecryptedContent">parseDecryptedContent()</a></dt> | ||
| <dd><p>Parsea el contenido desencriptado y lo almacena en un mapa clave-valor.</p> | ||
| </dd> | ||
| <dt><a href="#decrypt">decrypt(encryptedText, password)</a> ⇒ <code>string</code></dt> | ||
| <dd><p>Desencripta un texto cifrado con AES-GCM usando una clave derivada con PBKDF2.</p> | ||
| </dd> | ||
| <dt><a href="#getKey">getKey(keyName)</a> ⇒ <code>string</code></dt> | ||
| <dd><p>Obtiene el valor de una clave como String.</p> | ||
| </dd> | ||
| <dt><a href="#extractEncryptedKey">extractEncryptedKey(content)</a> ⇒ <code>string</code> | <code>null</code></dt> | ||
| <dd><p>Extrae la clave cifrada desde el contenido del archivo.</p> | ||
| </dd> | ||
| <dt><a href="#extractEncryptedData">extractEncryptedData(content)</a> ⇒ <code>string</code> | <code>null</code></dt> | ||
| <dd><p>Extrae los datos cifrados desde el contenido del archivo.</p> | ||
| </dd> | ||
| </dl> | ||
| <a name="AsimetricUtils"></a> | ||
| ## AsimetricUtils | ||
| La clase AsimetricUtils proporciona métodos para trabajar con encriptación y desencriptación | ||
| usando criptografía asimétrica, específicamente con el algoritmo RSA. Incluye funcionalidades | ||
| para generar pares de claves (pública y privada), guardar y cargar claves desde archivos, | ||
| y encriptar/desencriptar datos. | ||
| A utility class for asymmetric encryption using RSA. | ||
| Provides functions for generating, storing, retrieving, encrypting, and decrypting data securely. | ||
@@ -64,5 +45,5 @@ **Kind**: global class | ||
| * [.savePublicKey(publicKey, filePath)](#AsimetricUtils.savePublicKey) | ||
| * [.loadPublicKey(filePath)](#AsimetricUtils.loadPublicKey) ⇒ <code>Buffer</code> | ||
| * [.loadPublicKey(filePath)](#AsimetricUtils.loadPublicKey) ⇒ <code>crypto.KeyObject</code> | ||
| * [.savePrivateKey(privateKey, filePath)](#AsimetricUtils.savePrivateKey) | ||
| * [.loadPrivateKey(filePath)](#AsimetricUtils.loadPrivateKey) ⇒ <code>Buffer</code> | ||
| * [.loadPrivateKey(filePath)](#AsimetricUtils.loadPrivateKey) ⇒ <code>crypto.KeyObject</code> | ||
| * [.encryptWithPublicKey(data, publicKey)](#AsimetricUtils.encryptWithPublicKey) ⇒ <code>Buffer</code> | ||
@@ -74,9 +55,9 @@ * [.decryptWithPrivateKey(encryptedData, privateKey)](#AsimetricUtils.decryptWithPrivateKey) ⇒ <code>string</code> | ||
| ### AsimetricUtils.generateRSAKeyPair(keySize) ⇒ <code>Object</code> | ||
| Genera un par de claves públicas y privadas usando el algoritmo RSA. | ||
| Generates an RSA key pair (public and private keys). | ||
| **Kind**: static method of [<code>AsimetricUtils</code>](#AsimetricUtils) | ||
| **Returns**: <code>Object</code> - Un objeto que contiene la clave pública y la clave privada. | ||
| **Returns**: <code>Object</code> - An object containing the keys in PEM format. | ||
| **Throws**: | ||
| - <code>Error</code> Si el algoritmo RSA no está disponible en el entorno. | ||
| - <code>Error</code> If key generation fails. | ||
@@ -86,8 +67,15 @@ | ||
| | --- | --- | --- | | ||
| | keySize | <code>number</code> | El tamaño de la clave en bits. Generalmente, 2048 bits es adecuado para RSA. | | ||
| | keySize | <code>number</code> | The size of the RSA key in bits (recommended: 2048 or 4096). | | ||
| **Example** | ||
| ```js | ||
| // Generate a 2048-bit RSA key pair | ||
| const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| console.log("Public Key:\n", keys.publicKey); | ||
| console.log("Private Key:\n", keys.privateKey); | ||
| ``` | ||
| <a name="AsimetricUtils.savePublicKey"></a> | ||
| ### AsimetricUtils.savePublicKey(publicKey, filePath) | ||
| Guarda una clave pública en un archivo. | ||
| Saves a public key to a file. | ||
@@ -97,3 +85,3 @@ **Kind**: static method of [<code>AsimetricUtils</code>](#AsimetricUtils) | ||
| - <code>Error</code> Si ocurre un error al escribir en el archivo. | ||
| - <code>Error</code> If the file cannot be written. | ||
@@ -103,15 +91,21 @@ | ||
| | --- | --- | --- | | ||
| | publicKey | <code>Buffer</code> | La clave pública que se quiere guardar. | | ||
| | filePath | <code>string</code> | La ruta del archivo donde se guardará la clave. | | ||
| | publicKey | <code>string</code> | The public key in PEM format. | | ||
| | filePath | <code>string</code> | The file path where the key should be saved. | | ||
| **Example** | ||
| ```js | ||
| const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| AsimetricUtils.savePublicKey(keys.publicKey, './public.pem'); | ||
| console.log("Public key saved successfully!"); | ||
| ``` | ||
| <a name="AsimetricUtils.loadPublicKey"></a> | ||
| ### AsimetricUtils.loadPublicKey(filePath) ⇒ <code>Buffer</code> | ||
| Carga una clave pública desde un archivo. | ||
| ### AsimetricUtils.loadPublicKey(filePath) ⇒ <code>crypto.KeyObject</code> | ||
| Loads a public key from a file. | ||
| **Kind**: static method of [<code>AsimetricUtils</code>](#AsimetricUtils) | ||
| **Returns**: <code>Buffer</code> - La clave pública leída desde el archivo. | ||
| **Returns**: <code>crypto.KeyObject</code> - The loaded public key. | ||
| **Throws**: | ||
| - <code>Error</code> Si ocurre un error al leer el archivo. | ||
| - <code>Error</code> If the file cannot be read. | ||
@@ -121,8 +115,13 @@ | ||
| | --- | --- | --- | | ||
| | filePath | <code>string</code> | La ruta del archivo donde se encuentra la clave pública. | | ||
| | filePath | <code>string</code> | The path of the file containing the public key. | | ||
| **Example** | ||
| ```js | ||
| const publicKey = AsimetricUtils.loadPublicKey('./public.pem'); | ||
| console.log("Loaded Public Key:\n", publicKey); | ||
| ``` | ||
| <a name="AsimetricUtils.savePrivateKey"></a> | ||
| ### AsimetricUtils.savePrivateKey(privateKey, filePath) | ||
| Guarda una clave privada en un archivo. | ||
| Saves a private key to a file. | ||
@@ -132,3 +131,3 @@ **Kind**: static method of [<code>AsimetricUtils</code>](#AsimetricUtils) | ||
| - <code>Error</code> Si ocurre un error al escribir en el archivo. | ||
| - <code>Error</code> If the file cannot be written. | ||
@@ -138,15 +137,21 @@ | ||
| | --- | --- | --- | | ||
| | privateKey | <code>Buffer</code> | La clave privada que se quiere guardar. | | ||
| | filePath | <code>string</code> | La ruta del archivo donde se guardará la clave. | | ||
| | privateKey | <code>string</code> | The private key in PEM format. | | ||
| | filePath | <code>string</code> | The file path where the key should be saved. | | ||
| **Example** | ||
| ```js | ||
| const keys = AsimetricUtils.generateRSAKeyPair(2048); | ||
| AsimetricUtils.savePrivateKey(keys.privateKey, './private.pem'); | ||
| console.log("Private key saved successfully!"); | ||
| ``` | ||
| <a name="AsimetricUtils.loadPrivateKey"></a> | ||
| ### AsimetricUtils.loadPrivateKey(filePath) ⇒ <code>Buffer</code> | ||
| Carga una clave privada desde un archivo. | ||
| ### AsimetricUtils.loadPrivateKey(filePath) ⇒ <code>crypto.KeyObject</code> | ||
| Loads a private key from a file. | ||
| **Kind**: static method of [<code>AsimetricUtils</code>](#AsimetricUtils) | ||
| **Returns**: <code>Buffer</code> - La clave privada leída desde el archivo. | ||
| **Returns**: <code>crypto.KeyObject</code> - The loaded private key. | ||
| **Throws**: | ||
| - <code>Error</code> Si ocurre un error al leer el archivo. | ||
| - <code>Error</code> If the file cannot be read. | ||
@@ -156,14 +161,19 @@ | ||
| | --- | --- | --- | | ||
| | filePath | <code>string</code> | La ruta del archivo donde se encuentra la clave privada. | | ||
| | filePath | <code>string</code> | The path of the file containing the private key. | | ||
| **Example** | ||
| ```js | ||
| const privateKey = AsimetricUtils.loadPrivateKey('./private.pem'); | ||
| console.log("Loaded Private Key:\n", privateKey); | ||
| ``` | ||
| <a name="AsimetricUtils.encryptWithPublicKey"></a> | ||
| ### AsimetricUtils.encryptWithPublicKey(data, publicKey) ⇒ <code>Buffer</code> | ||
| Encripta un mensaje utilizando la clave pública (RSA). | ||
| Encrypts a message using a public key. | ||
| **Kind**: static method of [<code>AsimetricUtils</code>](#AsimetricUtils) | ||
| **Returns**: <code>Buffer</code> - El mensaje encriptado como un Buffer. | ||
| **Returns**: <code>Buffer</code> - The encrypted message. | ||
| **Throws**: | ||
| - <code>Error</code> Si ocurre un error durante la encriptación. | ||
| - <code>Error</code> If encryption fails. | ||
@@ -173,15 +183,21 @@ | ||
| | --- | --- | --- | | ||
| | data | <code>string</code> | El mensaje que se desea encriptar (en texto plano). | | ||
| | publicKey | <code>Buffer</code> | La clave pública utilizada para encriptar el mensaje. | | ||
| | data | <code>string</code> | The plaintext message to encrypt. | | ||
| | publicKey | <code>crypto.KeyObject</code> | The public key used for encryption. | | ||
| **Example** | ||
| ```js | ||
| const publicKey = AsimetricUtils.loadPublicKey('./public.pem'); | ||
| const encrypted = AsimetricUtils.encryptWithPublicKey("Hello, World!", publicKey); | ||
| console.log("Encrypted Data:", encrypted.toString('base64')); | ||
| ``` | ||
| <a name="AsimetricUtils.decryptWithPrivateKey"></a> | ||
| ### AsimetricUtils.decryptWithPrivateKey(encryptedData, privateKey) ⇒ <code>string</code> | ||
| Desencripta un mensaje utilizando la clave privada (RSA). | ||
| Decrypts a message using a private key. | ||
| **Kind**: static method of [<code>AsimetricUtils</code>](#AsimetricUtils) | ||
| **Returns**: <code>string</code> - El mensaje desencriptado en texto plano. | ||
| **Returns**: <code>string</code> - The decrypted message. | ||
| **Throws**: | ||
| - <code>Error</code> Si ocurre un error durante la desencriptación. | ||
| - <code>Error</code> If decryption fails. | ||
@@ -191,30 +207,88 @@ | ||
| | --- | --- | --- | | ||
| | encryptedData | <code>Buffer</code> | Los datos encriptados que se desean desencriptar. | | ||
| | privateKey | <code>Buffer</code> | La clave privada utilizada para desencriptar el mensaje. | | ||
| | encryptedData | <code>Buffer</code> | The encrypted data. | | ||
| | privateKey | <code>crypto.KeyObject</code> | The private key used for decryption. | | ||
| <a name="EncryptFile"></a> | ||
| **Example** | ||
| ```js | ||
| const privateKey = AsimetricUtils.loadPrivateKey('./private.pem'); | ||
| const decrypted = AsimetricUtils.decryptWithPrivateKey(encryptedData, privateKey); | ||
| console.log("Decrypted Message:", decrypted); | ||
| ``` | ||
| <a name="Decryptor"></a> | ||
| ## EncryptFile | ||
| Clase encargada de cifrar archivos utilizando una clave secreta fija y una clave aleatoria generada | ||
| dinámicamente para cada archivo. Aplica técnicas de ofuscación para aumentar la seguridad. | ||
| ## Decryptor | ||
| Utility class for decrypting AES-GCM encrypted data using a password-derived key. | ||
| **Kind**: global class | ||
| * [EncryptFile](#EncryptFile) | ||
| * _instance_ | ||
| * [.FIXED_SECRET](#EncryptFile+FIXED_SECRET) | ||
| * _static_ | ||
| * [.encryptFile(inputDecPath, outputEncPath)](#EncryptFile.encryptFile) | ||
| * [Decryptor](#Decryptor) | ||
| * [.ITERATIONS](#Decryptor.ITERATIONS) | ||
| * [.SALT_LENGTH](#Decryptor.SALT_LENGTH) | ||
| * [.KEY_LENGTH](#Decryptor.KEY_LENGTH) | ||
| * [.IV_LENGTH](#Decryptor.IV_LENGTH) | ||
| * [.AUTH_TAG_LENGTH](#Decryptor.AUTH_TAG_LENGTH) | ||
| * [.decrypt(encryptedText, password)](#Decryptor.decrypt) ⇒ <code>string</code> \| <code>undefined</code> | ||
| <a name="EncryptFile+FIXED_SECRET"></a> | ||
| <a name="Decryptor.ITERATIONS"></a> | ||
| ### encryptFile.FIXED\_SECRET | ||
| Clave secreta fija utilizada para cifrar la clave aleatoria del archivo. | ||
| Esta clave debe mantenerse segura y nunca exponerse públicamente. | ||
| ### Decryptor.ITERATIONS | ||
| Number of PBKDF2 iterations for key derivation (higher = more secure but slower). | ||
| **Kind**: instance property of [<code>EncryptFile</code>](#EncryptFile) | ||
| **Kind**: static property of [<code>Decryptor</code>](#Decryptor) | ||
| <a name="Decryptor.SALT_LENGTH"></a> | ||
| ### Decryptor.SALT\_LENGTH | ||
| Salt length in bytes (16 bytes = 128 bits, recommended for security). | ||
| **Kind**: static property of [<code>Decryptor</code>](#Decryptor) | ||
| <a name="Decryptor.KEY_LENGTH"></a> | ||
| ### Decryptor.KEY\_LENGTH | ||
| Key length in bytes (32 bytes = 256 bits, AES-256). | ||
| **Kind**: static property of [<code>Decryptor</code>](#Decryptor) | ||
| <a name="Decryptor.IV_LENGTH"></a> | ||
| ### Decryptor.IV\_LENGTH | ||
| Initialization Vector (IV) length in bytes (12 bytes is recommended for AES-GCM). | ||
| **Kind**: static property of [<code>Decryptor</code>](#Decryptor) | ||
| <a name="Decryptor.AUTH_TAG_LENGTH"></a> | ||
| ### Decryptor.AUTH\_TAG\_LENGTH | ||
| Authentication Tag length in bytes (16 bytes ensures message integrity). | ||
| **Kind**: static property of [<code>Decryptor</code>](#Decryptor) | ||
| <a name="Decryptor.decrypt"></a> | ||
| ### Decryptor.decrypt(encryptedText, password) ⇒ <code>string</code> \| <code>undefined</code> | ||
| Decrypts an AES-GCM encrypted message using a password. | ||
| **Kind**: static method of [<code>Decryptor</code>](#Decryptor) | ||
| **Returns**: <code>string</code> \| <code>undefined</code> - - The decrypted plaintext string, or `undefined` if decryption fails. | ||
| **Throws**: | ||
| - <code>Error</code> If decryption fails. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | encryptedText | <code>string</code> | The Base64-encoded encrypted string (contains salt + IV + cipherText + authTag). | | ||
| | password | <code>string</code> | The password used to derive the decryption key. | | ||
| **Example** | ||
| ```js | ||
| const decrypted = Decryptor.decrypt(encryptedData, "my_secure_password"); | ||
| console.log("Decrypted Text:", decrypted); | ||
| ``` | ||
| <a name="EncryptFile"></a> | ||
| ## EncryptFile | ||
| Utility class for encrypting files using a combination of random per-file keys and a fixed secret key. | ||
| **Kind**: global class | ||
| <a name="EncryptFile.encryptFile"></a> | ||
| ### EncryptFile.encryptFile(inputDecPath, outputEncPath) | ||
| Cifra un archivo de texto plano y lo guarda en una nueva ubicación con formato ofuscado. | ||
| Encrypts a plaintext file and saves it to a new location with obfuscation techniques applied. | ||
@@ -224,3 +298,3 @@ **Kind**: static method of [<code>EncryptFile</code>](#EncryptFile) | ||
| - <code>Error</code> En caso de error al leer/escribir archivos o durante el proceso de cifrado. | ||
| - <code>Error</code> If file operations fail or encryption encounters an error. | ||
@@ -230,9 +304,85 @@ | ||
| | --- | --- | --- | | ||
| | inputDecPath | <code>string</code> | Ruta del archivo de entrada en texto plano (sin cifrar). | | ||
| | outputEncPath | <code>string</code> | Ruta del archivo de salida cifrado. | | ||
| | inputDecPath | <code>string</code> | Path to the **plaintext** input file. | | ||
| | outputEncPath | <code>string</code> | Path where the **encrypted** file will be saved. | | ||
| **Example** | ||
| ```js | ||
| EncryptFile.encryptFile("data.txt", "data.enc"); | ||
| ``` | ||
| <a name="Encryptor"></a> | ||
| ## Encryptor | ||
| Provides AES-GCM encryption with PBKDF2 key derivation for strong security. | ||
| **Kind**: global class | ||
| * [Encryptor](#Encryptor) | ||
| * [.ITERATIONS](#Encryptor.ITERATIONS) | ||
| * [.SALT_LENGTH](#Encryptor.SALT_LENGTH) | ||
| * [.KEY_LENGTH](#Encryptor.KEY_LENGTH) | ||
| * [.IV_LENGTH](#Encryptor.IV_LENGTH) | ||
| * [.AUTH_TAG_LENGTH](#Encryptor.AUTH_TAG_LENGTH) | ||
| * [.encrypt(plainText, password)](#Encryptor.encrypt) ⇒ <code>string</code> | ||
| <a name="Encryptor.ITERATIONS"></a> | ||
| ### Encryptor.ITERATIONS | ||
| Number of iterations for PBKDF2 (increases brute-force resistance). | ||
| Higher values = **more security** but slower processing. | ||
| **Kind**: static property of [<code>Encryptor</code>](#Encryptor) | ||
| <a name="Encryptor.SALT_LENGTH"></a> | ||
| ### Encryptor.SALT\_LENGTH | ||
| Length of the salt in bytes (16 bytes = 128 bits). | ||
| Salt ensures **each encryption is unique**, even with the same password. | ||
| **Kind**: static property of [<code>Encryptor</code>](#Encryptor) | ||
| <a name="Encryptor.KEY_LENGTH"></a> | ||
| ### Encryptor.KEY\_LENGTH | ||
| AES-256 key length in bytes (32 bytes = 256 bits). | ||
| AES-256 requires a **32-byte key** for maximum security. | ||
| **Kind**: static property of [<code>Encryptor</code>](#Encryptor) | ||
| <a name="Encryptor.IV_LENGTH"></a> | ||
| ### Encryptor.IV\_LENGTH | ||
| IV (Initialization Vector) length in bytes (12 bytes = recommended for GCM mode). | ||
| IV ensures **non-repeating ciphertext** for the same input. | ||
| **Kind**: static property of [<code>Encryptor</code>](#Encryptor) | ||
| <a name="Encryptor.AUTH_TAG_LENGTH"></a> | ||
| ### Encryptor.AUTH\_TAG\_LENGTH | ||
| Authentication Tag length in bytes (16 bytes = 128 bits). | ||
| Ensures the integrity of the ciphertext and prevents tampering. | ||
| **Kind**: static property of [<code>Encryptor</code>](#Encryptor) | ||
| <a name="Encryptor.encrypt"></a> | ||
| ### Encryptor.encrypt(plainText, password) ⇒ <code>string</code> | ||
| Encrypts a plaintext string using **AES-256-GCM** with a password-derived key. | ||
| **Kind**: static method of [<code>Encryptor</code>](#Encryptor) | ||
| **Returns**: <code>string</code> - - The encrypted text, encoded in Base64 (salt + IV + cipherText + authTag). | ||
| **Throws**: | ||
| - <code>Error</code> - If encryption fails. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | plainText | <code>string</code> | The text to be encrypted. | | ||
| | password | <code>string</code> | The password used to derive the encryption key. | | ||
| **Example** | ||
| ```js | ||
| const encrypted = Encryptor.encrypt("Hello, world!", "my_secure_password"); | ||
| console.log(encrypted); // Encrypted text in Base64 format | ||
| ``` | ||
| <a name="HashingUtils"></a> | ||
| ## HashingUtils | ||
| Clase segura para hashing con PBKDF2, SHA-512, SHA-256, salt aleatorio y un pepper secreto. | ||
| Provides methods for securely hashing passwords using PBKDF2, salt, and a pepper. | ||
@@ -244,7 +394,7 @@ **Kind**: global class | ||
| * [.generateSecureHashSHA256(input)](#HashingUtils.generateSecureHashSHA256) ⇒ <code>string</code> | ||
| * [.verifyHashSHA512(input, storedHashWithSalt)](#HashingUtils.verifyHashSHA512) ⇒ <code>boolean</code> | ||
| * [.verifyHashSHA256(input, storedHashWithSalt)](#HashingUtils.verifyHashSHA256) ⇒ <code>boolean</code> | ||
| * [.deriveKey(input, salt, useSHA512)](#HashingUtils.deriveKey) ⇒ <code>Buffer</code> | ||
| * [.encodeBase64(data)](#HashingUtils.encodeBase64) ⇒ <code>string</code> | ||
| * [.decodeBase64(base64)](#HashingUtils.decodeBase64) ⇒ <code>Buffer</code> | ||
| * [.verifyHashSHA512(input, storedHash)](#HashingUtils.verifyHashSHA512) ⇒ <code>boolean</code> | ||
| * [.verifyHashSHA256(input, storedHash)](#HashingUtils.verifyHashSHA256) ⇒ <code>boolean</code> | ||
| * [.generateSecureHash(input, algorithm)](#HashingUtils.generateSecureHash) ⇒ <code>string</code> | ||
| * [.verifyHash(input, storedHash, algorithm)](#HashingUtils.verifyHash) ⇒ <code>boolean</code> | ||
| * [.deriveKey(input, salt, algorithm)](#HashingUtils.deriveKey) ⇒ <code>Buffer</code> | ||
| * [.generateSalt()](#HashingUtils.generateSalt) ⇒ <code>Buffer</code> | ||
@@ -255,10 +405,10 @@ | ||
| ### HashingUtils.generateSecureHashSHA512(input) ⇒ <code>string</code> | ||
| Genera un hash seguro usando PBKDF2 con HMAC-SHA-512, salt aleatorio y un pepper secreto. | ||
| Generates a secure SHA-512 hash using PBKDF2, a random salt, and a secret pepper. | ||
| **Kind**: static method of [<code>HashingUtils</code>](#HashingUtils) | ||
| **Returns**: <code>string</code> - Cadena en formato Base64 con el salt y el hash concatenados y separados por '$'. | ||
| **Returns**: <code>string</code> - The Base64 encoded hash (`salt$hash` format). | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | input | <code>string</code> | El texto plano que se va a hashear. | | ||
| | input | <code>string</code> | The plain text to hash. | | ||
@@ -268,74 +418,77 @@ <a name="HashingUtils.generateSecureHashSHA256"></a> | ||
| ### HashingUtils.generateSecureHashSHA256(input) ⇒ <code>string</code> | ||
| Genera un hash seguro usando PBKDF2 con HMAC-SHA-256, salt aleatorio y un pepper secreto. | ||
| Generates a secure SHA-256 hash using PBKDF2, a random salt, and a secret pepper. | ||
| **Kind**: static method of [<code>HashingUtils</code>](#HashingUtils) | ||
| **Returns**: <code>string</code> - Cadena en formato Base64 con el salt y el hash concatenados y separados por '$'. | ||
| **Returns**: <code>string</code> - The Base64 encoded hash (`salt$hash` format). | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | input | <code>string</code> | El texto plano que se va a hashear. | | ||
| | input | <code>string</code> | The plain text to hash. | | ||
| <a name="HashingUtils.verifyHashSHA512"></a> | ||
| ### HashingUtils.verifyHashSHA512(input, storedHashWithSalt) ⇒ <code>boolean</code> | ||
| Verifica si un hash corresponde al texto plano dado usando SHA-512. | ||
| ### HashingUtils.verifyHashSHA512(input, storedHash) ⇒ <code>boolean</code> | ||
| Verifies if a SHA-512 hash matches the plain text. | ||
| **Kind**: static method of [<code>HashingUtils</code>](#HashingUtils) | ||
| **Returns**: <code>boolean</code> - true si el hash generado coincide con el almacenado; de lo contrario, false. | ||
| **Returns**: <code>boolean</code> - `true` if the hash matches, `false` otherwise. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | input | <code>string</code> | El texto plano a verificar. | | ||
| | storedHashWithSalt | <code>string</code> | El hash almacenado (salt$hash en Base64). | | ||
| | input | <code>string</code> | The plain text to check. | | ||
| | storedHash | <code>string</code> | The stored hash (`salt$hash` in Base64). | | ||
| <a name="HashingUtils.verifyHashSHA256"></a> | ||
| ### HashingUtils.verifyHashSHA256(input, storedHashWithSalt) ⇒ <code>boolean</code> | ||
| Verifica si un hash corresponde al texto plano dado usando SHA-256. | ||
| ### HashingUtils.verifyHashSHA256(input, storedHash) ⇒ <code>boolean</code> | ||
| Verifies if a SHA-256 hash matches the plain text. | ||
| **Kind**: static method of [<code>HashingUtils</code>](#HashingUtils) | ||
| **Returns**: <code>boolean</code> - true si el hash generado coincide con el almacenado; de lo contrario, false. | ||
| **Returns**: <code>boolean</code> - `true` if the hash matches, `false` otherwise. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | input | <code>string</code> | El texto plano a verificar. | | ||
| | storedHashWithSalt | <code>string</code> | El hash almacenado (salt$hash en Base64). | | ||
| | input | <code>string</code> | The plain text to check. | | ||
| | storedHash | <code>string</code> | The stored hash (`salt$hash` in Base64). | | ||
| <a name="HashingUtils.deriveKey"></a> | ||
| <a name="HashingUtils.generateSecureHash"></a> | ||
| ### HashingUtils.deriveKey(input, salt, useSHA512) ⇒ <code>Buffer</code> | ||
| Deriva una clave usando PBKDF2 con HMAC-SHA-512 o HMAC-SHA-256 y un pepper. | ||
| ### HashingUtils.generateSecureHash(input, algorithm) ⇒ <code>string</code> | ||
| Generates a secure hash using PBKDF2 + Salt + Pepper. | ||
| **Kind**: static method of [<code>HashingUtils</code>](#HashingUtils) | ||
| **Returns**: <code>Buffer</code> - Array de bytes con el hash derivado. | ||
| **Returns**: <code>string</code> - The Base64 encoded hash (`salt$hash` format). | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | input | <code>string</code> | Texto plano a convertir en hash. | | ||
| | salt | <code>Buffer</code> | Salt aleatorio utilizado en el hashing. | | ||
| | useSHA512 | <code>boolean</code> | Si es verdadero, usa SHA-512, de lo contrario usa SHA-256. | | ||
| | input | <code>string</code> | The plain text to hash. | | ||
| | algorithm | <code>"sha512"</code> \| <code>"sha256"</code> | The hashing algorithm to use. | | ||
| <a name="HashingUtils.encodeBase64"></a> | ||
| <a name="HashingUtils.verifyHash"></a> | ||
| ### HashingUtils.encodeBase64(data) ⇒ <code>string</code> | ||
| Convierte un array de bytes en una cadena Base64. | ||
| ### HashingUtils.verifyHash(input, storedHash, algorithm) ⇒ <code>boolean</code> | ||
| Verifies if a hash corresponds to the plain text. | ||
| **Kind**: static method of [<code>HashingUtils</code>](#HashingUtils) | ||
| **Returns**: <code>string</code> - Cadena codificada en Base64. | ||
| **Returns**: <code>boolean</code> - `true` if the hash matches, `false` otherwise. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | data | <code>Buffer</code> | Datos en bytes. | | ||
| | input | <code>string</code> | The plain text to check. | | ||
| | storedHash | <code>string</code> | The stored hash (`salt$hash` in Base64). | | ||
| | algorithm | <code>"sha512"</code> \| <code>"sha256"</code> | The hashing algorithm used. | | ||
| <a name="HashingUtils.decodeBase64"></a> | ||
| <a name="HashingUtils.deriveKey"></a> | ||
| ### HashingUtils.decodeBase64(base64) ⇒ <code>Buffer</code> | ||
| Decodifica una cadena Base64 en un array de bytes. | ||
| ### HashingUtils.deriveKey(input, salt, algorithm) ⇒ <code>Buffer</code> | ||
| Derives a key using PBKDF2 + Pepper. | ||
| **Kind**: static method of [<code>HashingUtils</code>](#HashingUtils) | ||
| **Returns**: <code>Buffer</code> - Array de bytes decodificado. | ||
| **Returns**: <code>Buffer</code> - The derived hash. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | base64 | <code>string</code> | Cadena en Base64. | | ||
| | input | <code>string</code> | The plain text. | | ||
| | salt | <code>Buffer</code> | The salt used in hashing. | | ||
| | algorithm | <code>"sha512"</code> \| <code>"sha256"</code> | The hashing algorithm used. | | ||
@@ -345,11 +498,10 @@ <a name="HashingUtils.generateSalt"></a> | ||
| ### HashingUtils.generateSalt() ⇒ <code>Buffer</code> | ||
| Genera un salt aleatorio de longitud fija. | ||
| Generates a random salt. | ||
| **Kind**: static method of [<code>HashingUtils</code>](#HashingUtils) | ||
| **Returns**: <code>Buffer</code> - Un buffer con un salt aleatorio. | ||
| **Returns**: <code>Buffer</code> - The random salt. | ||
| <a name="KeyGenerator"></a> | ||
| ## KeyGenerator | ||
| Clase KeyGenerator que proporciona métodos para generar claves seguras | ||
| a partir de contraseñas y sal (salt), utilizando algoritmos criptográficos robustos. | ||
| Class for generating secure keys and random passwords using strong cryptography. | ||
@@ -359,3 +511,3 @@ **Kind**: global class | ||
| * [KeyGenerator](#KeyGenerator) | ||
| * [.generateKey(password, salt)](#KeyGenerator.generateKey) ⇒ <code>Buffer</code> | ||
| * [.generateKey(password, salt)](#KeyGenerator.generateKey) ⇒ <code>Promise.<Buffer></code> | ||
| * [.generateSalt()](#KeyGenerator.generateSalt) ⇒ <code>Buffer</code> | ||
@@ -366,13 +518,16 @@ * [.generateSecurePassword(length)](#KeyGenerator.generateSecurePassword) ⇒ <code>string</code> | ||
| ### KeyGenerator.generateKey(password, salt) ⇒ <code>Buffer</code> | ||
| Genera una clave secreta AES a partir de una contraseña y un salt utilizando PBKDF2. | ||
| Este proceso deriva una clave segura a partir de una contraseña utilizando el salt y el algoritmo PBKDF2. | ||
| ### KeyGenerator.generateKey(password, salt) ⇒ <code>Promise.<Buffer></code> | ||
| Generates a secure AES key from a password and salt using PBKDF2 with HMAC-SHA-512. | ||
| **Kind**: static method of [<code>KeyGenerator</code>](#KeyGenerator) | ||
| **Returns**: <code>Buffer</code> - La clave generada para AES. | ||
| **Returns**: <code>Promise.<Buffer></code> - A secure 256-bit (32-byte) derived key. | ||
| **Throws**: | ||
| - <code>Error</code> If an error occurs during the key generation. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | password | <code>string</code> | La contraseña que se utilizará para generar la clave. | | ||
| | salt | <code>Buffer</code> | El salt aleatorio utilizado para derivar la clave. | | ||
| | password | <code>string</code> | The password used to generate the key. | | ||
| | salt | <code>Buffer</code> | The random salt used in the key derivation. | | ||
@@ -382,23 +537,16 @@ <a name="KeyGenerator.generateSalt"></a> | ||
| ### KeyGenerator.generateSalt() ⇒ <code>Buffer</code> | ||
| Genera un salt aleatorio de longitud fija utilizando crypto.randomBytes. | ||
| El salt se utiliza para diversificar los resultados de la función de derivación de claves. | ||
| Generates a random salt of fixed length. | ||
| **Kind**: static method of [<code>KeyGenerator</code>](#KeyGenerator) | ||
| **Returns**: <code>Buffer</code> - Un buffer con un salt aleatorio. | ||
| **Returns**: <code>Buffer</code> - A random 16-byte salt buffer. | ||
| <a name="KeyGenerator.generateSecurePassword"></a> | ||
| ### KeyGenerator.generateSecurePassword(length) ⇒ <code>string</code> | ||
| Genera una contraseña segura de la longitud especificada. | ||
| <p> | ||
| Este método utiliza un generador de números aleatorios criptográficamente seguro | ||
| ([crypto.randomBytes](crypto.randomBytes)) para crear una contraseña aleatoria con caracteres | ||
| alfanuméricos y especiales. La contraseña generada es adecuada para su uso en | ||
| autenticación y almacenamiento seguro. | ||
| </p> | ||
| Generates a secure random password containing alphanumeric characters and special symbols. | ||
| **Kind**: static method of [<code>KeyGenerator</code>](#KeyGenerator) | ||
| **Returns**: <code>string</code> - Una contraseña segura generada aleatoriamente. | ||
| **Returns**: <code>string</code> - A securely generated random password. | ||
| **Throws**: | ||
| - <code>Error</code> Si la longitud especificada es menor o igual a 0. | ||
| - <code>Error</code> If the length is less than or equal to 0. | ||
@@ -408,142 +556,172 @@ | ||
| | --- | --- | --- | | ||
| | length | <code>number</code> | La longitud de la contraseña generada. Debe ser un número positivo mayor a 0. | | ||
| | length | <code>number</code> | The length of the generated password (minimum 1). | | ||
| <a name="SecurityUtils"></a> | ||
| <a name="SecureKeys"></a> | ||
| ## SecurityUtils | ||
| Clase SecurityUtils con funciones avanzadas de seguridad, | ||
| incluyendo generación y verificación de HMAC con SHA-512, claves seguras y más. | ||
| ## SecureKeys | ||
| Class for managing secure key storage, decryption, and retrieval. | ||
| This class supports loading encrypted data, decrypting it, and storing it in memory for fast access. | ||
| **Kind**: global class | ||
| * [SecurityUtils](#SecurityUtils) | ||
| * [.generateHMAC(message, secretKey)](#SecurityUtils.generateHMAC) ⇒ <code>string</code> | ||
| * [.verifyHMAC(message, secretKey, receivedHMAC)](#SecurityUtils.verifyHMAC) ⇒ <code>boolean</code> | ||
| * [.generateSecureKey(password, salt)](#SecurityUtils.generateSecureKey) ⇒ <code>string</code> | ||
| * [.generateRandomKey()](#SecurityUtils.generateRandomKey) ⇒ <code>string</code> | ||
| * [.generateSalt()](#SecurityUtils.generateSalt) ⇒ <code>Buffer</code> | ||
| * [SecureKeys](#SecureKeys) | ||
| * [.init(encFilePath)](#SecureKeys.init) ⇒ <code>Promise.<void></code> | ||
| * [.parseDecryptedContent()](#SecureKeys.parseDecryptedContent) | ||
| * [.decrypt(encryptedText, password)](#SecureKeys.decrypt) ⇒ <code>string</code> \| <code>undefined</code> | ||
| * [.getKey(keyName)](#SecureKeys.getKey) ⇒ <code>any</code> | ||
| * [.extractEncryptedKey(content)](#SecureKeys.extractEncryptedKey) ⇒ <code>string</code> \| <code>null</code> | ||
| * [.extractEncryptedData(content)](#SecureKeys.extractEncryptedData) ⇒ <code>string</code> \| <code>null</code> | ||
| <a name="SecurityUtils.generateHMAC"></a> | ||
| <a name="SecureKeys.init"></a> | ||
| ### SecurityUtils.generateHMAC(message, secretKey) ⇒ <code>string</code> | ||
| Genera un HMAC (Hashed Message Authentication Code) utilizando SHA-512 con una clave secreta segura. | ||
| ### SecureKeys.init(encFilePath) ⇒ <code>Promise.<void></code> | ||
| Initializes the class by loading and decrypting the content of an encrypted file. | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>string</code> - El HMAC generado en formato Base64. | ||
| **Kind**: static method of [<code>SecureKeys</code>](#SecureKeys) | ||
| **Returns**: <code>Promise.<void></code> - Resolves when the file is loaded and decrypted successfully. | ||
| **Throws**: | ||
| - <code>Error</code> If an error occurs during file reading or decryption. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | message | <code>string</code> | El mensaje que se va a autenticar. | | ||
| | secretKey | <code>string</code> | La clave secreta utilizada para generar el HMAC. | | ||
| | encFilePath | <code>string</code> | The path to the encrypted .enc file. | | ||
| <a name="SecurityUtils.verifyHMAC"></a> | ||
| <a name="SecureKeys.parseDecryptedContent"></a> | ||
| ### SecurityUtils.verifyHMAC(message, secretKey, receivedHMAC) ⇒ <code>boolean</code> | ||
| Verifica si un HMAC es válido comparándolo con un mensaje dado. | ||
| ### SecureKeys.parseDecryptedContent() | ||
| Parses the decrypted content and stores it in a key-value map. | ||
| Only processes lines that match the format: "| key -> value". | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>boolean</code> - {@code true} si el HMAC es válido, {@code false} en caso contrario. | ||
| **Kind**: static method of [<code>SecureKeys</code>](#SecureKeys) | ||
| <a name="SecureKeys.decrypt"></a> | ||
| ### SecureKeys.decrypt(encryptedText, password) ⇒ <code>string</code> \| <code>undefined</code> | ||
| Decrypts a given encrypted text using AES-GCM with a key derived from PBKDF2. | ||
| **Kind**: static method of [<code>SecureKeys</code>](#SecureKeys) | ||
| **Returns**: <code>string</code> \| <code>undefined</code> - The decrypted text or undefined if an error occurs. | ||
| **Throws**: | ||
| - <code>Error</code> If decryption fails. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | message | <code>string</code> | El mensaje original. | | ||
| | secretKey | <code>string</code> | La clave secreta utilizada para generar el HMAC. | | ||
| | receivedHMAC | <code>string</code> | El HMAC recibido. | | ||
| | encryptedText | <code>string</code> | The encrypted text in Base64. | | ||
| | password | <code>string</code> | The password used to derive the decryption key. | | ||
| <a name="SecurityUtils.generateSecureKey"></a> | ||
| <a name="SecureKeys.getKey"></a> | ||
| ### SecurityUtils.generateSecureKey(password, salt) ⇒ <code>string</code> | ||
| Genera una clave secreta segura utilizando PBKDF2 con HMAC-SHA-512. | ||
| ### SecureKeys.getKey(keyName) ⇒ <code>any</code> | ||
| Retrieves the value associated with a key from the in-memory key-value map. | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>string</code> - Una clave secreta segura en formato Base64. | ||
| **Kind**: static method of [<code>SecureKeys</code>](#SecureKeys) | ||
| **Returns**: <code>any</code> - The associated value, or null if the key does not exist. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | password | <code>string</code> | La contraseña base para derivar la clave. | | ||
| | salt | <code>Buffer</code> | Un valor aleatorio para fortalecer la clave. | | ||
| | keyName | <code>string</code> | The name of the key to retrieve. | | ||
| <a name="SecurityUtils.generateRandomKey"></a> | ||
| <a name="SecureKeys.extractEncryptedKey"></a> | ||
| ### SecurityUtils.generateRandomKey() ⇒ <code>string</code> | ||
| Genera una clave secreta aleatoria segura. | ||
| ### SecureKeys.extractEncryptedKey(content) ⇒ <code>string</code> \| <code>null</code> | ||
| Extracts the encrypted key from the encrypted file content. | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>string</code> - Una clave secreta en formato Base64. | ||
| <a name="SecurityUtils.generateSalt"></a> | ||
| **Kind**: static method of [<code>SecureKeys</code>](#SecureKeys) | ||
| **Returns**: <code>string</code> \| <code>null</code> - The encrypted key in Base64 format, or null if not found. | ||
| ### SecurityUtils.generateSalt() ⇒ <code>Buffer</code> | ||
| Genera un salt aleatorio seguro. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | content | <code>string</code> | The content of the encrypted file. | | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>Buffer</code> - Un salt aleatorio en bytes. | ||
| <a name="init"></a> | ||
| <a name="SecureKeys.extractEncryptedData"></a> | ||
| ## init(encFilePath) | ||
| Inicializa la clase cargando y desencriptando el contenido del archivo cifrado. | ||
| ### SecureKeys.extractEncryptedData(content) ⇒ <code>string</code> \| <code>null</code> | ||
| Extracts the encrypted data from the encrypted file content. | ||
| **Kind**: global function | ||
| **Throws**: | ||
| **Kind**: static method of [<code>SecureKeys</code>](#SecureKeys) | ||
| **Returns**: <code>string</code> \| <code>null</code> - The encrypted data in Base64 format, or null if not found. | ||
| - <code>Error</code> Si ocurre un error al leer o desencriptar el archivo | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | encFilePath | <code>string</code> | Ruta del archivo .enc | | ||
| | content | <code>string</code> | The content of the encrypted file. | | ||
| <a name="parseDecryptedContent"></a> | ||
| <a name="SecurityUtils"></a> | ||
| ## parseDecryptedContent() | ||
| Parsea el contenido desencriptado y lo almacena en un mapa clave-valor. | ||
| ## SecurityUtils | ||
| This class provides advanced security utilities, including HMAC generation and verification, | ||
| secure key generation using PBKDF2, random key and salt generation, and more. | ||
| **Kind**: global function | ||
| <a name="decrypt"></a> | ||
| **Kind**: global class | ||
| ## decrypt(encryptedText, password) ⇒ <code>string</code> | ||
| Desencripta un texto cifrado con AES-GCM usando una clave derivada con PBKDF2. | ||
| * [SecurityUtils](#SecurityUtils) | ||
| * [.generateHMAC(message, secretKey)](#SecurityUtils.generateHMAC) ⇒ <code>string</code> \| <code>undefined</code> | ||
| * [.verifyHMAC(message, secretKey, receivedHMAC)](#SecurityUtils.verifyHMAC) ⇒ <code>boolean</code> | ||
| * [.generateSecureKey(password, salt)](#SecurityUtils.generateSecureKey) ⇒ <code>string</code> \| <code>undefined</code> | ||
| * [.generateRandomKey()](#SecurityUtils.generateRandomKey) ⇒ <code>string</code> | ||
| * [.generateSalt()](#SecurityUtils.generateSalt) ⇒ <code>Buffer</code> | ||
| **Kind**: global function | ||
| **Returns**: <code>string</code> - Texto desencriptado. | ||
| <a name="SecurityUtils.generateHMAC"></a> | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | encryptedText | <code>string</code> | Texto cifrado en Base64. | | ||
| | password | <code>string</code> | Contraseña para derivar la clave. | | ||
| ### SecurityUtils.generateHMAC(message, secretKey) ⇒ <code>string</code> \| <code>undefined</code> | ||
| Generates an HMAC (Hashed Message Authentication Code) using SHA-512 with a secret key. | ||
| <a name="getKey"></a> | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>string</code> \| <code>undefined</code> - The generated HMAC in Base64 format, or undefined if an error occurs. | ||
| **Throws**: | ||
| ## getKey(keyName) ⇒ <code>string</code> | ||
| Obtiene el valor de una clave como String. | ||
| - <code>Error</code> If there is an error during HMAC generation. | ||
| **Kind**: global function | ||
| **Returns**: <code>string</code> - Valor asociado o null si no existe | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | keyName | <code>string</code> | Nombre de la clave | | ||
| | message | <code>string</code> | The message to authenticate. | | ||
| | secretKey | <code>string</code> | The secret key used to generate the HMAC. | | ||
| <a name="extractEncryptedKey"></a> | ||
| <a name="SecurityUtils.verifyHMAC"></a> | ||
| ## extractEncryptedKey(content) ⇒ <code>string</code> \| <code>null</code> | ||
| Extrae la clave cifrada desde el contenido del archivo. | ||
| ### SecurityUtils.verifyHMAC(message, secretKey, receivedHMAC) ⇒ <code>boolean</code> | ||
| Verifies if a given HMAC is valid by comparing it with the computed HMAC for the message. | ||
| **Kind**: global function | ||
| **Returns**: <code>string</code> \| <code>null</code> - La clave cifrada en Base64 | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>boolean</code> - Returns true if the HMAC is valid, false otherwise. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | content | <code>string</code> | Contenido del archivo cifrado | | ||
| | message | <code>string</code> | The original message. | | ||
| | secretKey | <code>string</code> | The secret key used to generate the HMAC. | | ||
| | receivedHMAC | <code>string</code> | The received HMAC to verify. | | ||
| <a name="extractEncryptedData"></a> | ||
| <a name="SecurityUtils.generateSecureKey"></a> | ||
| ## extractEncryptedData(content) ⇒ <code>string</code> \| <code>null</code> | ||
| Extrae los datos cifrados desde el contenido del archivo. | ||
| ### SecurityUtils.generateSecureKey(password, salt) ⇒ <code>string</code> \| <code>undefined</code> | ||
| Generates a secure secret key using PBKDF2 with HMAC-SHA-512. | ||
| **Kind**: global function | ||
| **Returns**: <code>string</code> \| <code>null</code> - Los datos cifrados en Base64 | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>string</code> \| <code>undefined</code> - A secure secret key in Base64 format, or undefined if an error occurs. | ||
| **Throws**: | ||
| - <code>Error</code> If there is an error during key generation. | ||
| | Param | Type | Description | | ||
| | --- | --- | --- | | ||
| | content | <code>string</code> | Contenido del archivo cifrado | | ||
| | password | <code>string</code> | The base password to derive the key. | | ||
| | salt | <code>Buffer</code> | A random value to strengthen the key. | | ||
| <a name="SecurityUtils.generateRandomKey"></a> | ||
| ### SecurityUtils.generateRandomKey() ⇒ <code>string</code> | ||
| Generates a secure random secret key. | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>string</code> - A random secret key in Base64 format. | ||
| <a name="SecurityUtils.generateSalt"></a> | ||
| ### SecurityUtils.generateSalt() ⇒ <code>Buffer</code> | ||
| Generates a secure random salt. | ||
| **Kind**: static method of [<code>SecurityUtils</code>](#SecurityUtils) | ||
| **Returns**: <code>Buffer</code> - A random salt in bytes (256 bits). |
| const fs = require('fs'); | ||
| const crypto = require('crypto'); | ||
| /** | ||
| * La clase AsimetricUtils proporciona métodos para trabajar con encriptación y desencriptación | ||
| * usando criptografía asimétrica, específicamente con el algoritmo RSA. Incluye funcionalidades | ||
| * para generar pares de claves (pública y privada), guardar y cargar claves desde archivos, | ||
| * y encriptar/desencriptar datos. | ||
| */ | ||
| class AsimetricUtils { | ||
| /** | ||
| * Genera un par de claves públicas y privadas usando el algoritmo RSA. | ||
| * | ||
| * @param {number} keySize El tamaño de la clave en bits. Generalmente, 2048 bits es adecuado para RSA. | ||
| * @returns {Object} Un objeto que contiene la clave pública y la clave privada. | ||
| * @throws {Error} Si el algoritmo RSA no está disponible en el entorno. | ||
| */ | ||
| static generateRSAKeyPair(keySize) { | ||
| try { | ||
| // Genera el par de claves RSA | ||
| const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { | ||
| modulusLength: keySize, // Tamaño de la clave en bits (2048 por defecto) | ||
| }); | ||
| return { publicKey, privateKey }; | ||
| } catch (error) { | ||
| throw new Error("Error generando el par de claves RSA: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Guarda una clave pública en un archivo. | ||
| * | ||
| * @param {Buffer} publicKey La clave pública que se quiere guardar. | ||
| * @param {string} filePath La ruta del archivo donde se guardará la clave. | ||
| * @throws {Error} Si ocurre un error al escribir en el archivo. | ||
| */ | ||
| static savePublicKey(publicKey, filePath) { | ||
| try { | ||
| const pemPublicKey = publicKey.export({ type: 'spki', format: 'pem' }); | ||
| fs.writeFileSync(filePath, pemPublicKey); | ||
| } catch (error) { | ||
| throw new Error("Error al guardar la clave pública: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Carga una clave pública desde un archivo. | ||
| * | ||
| * @param {string} filePath La ruta del archivo donde se encuentra la clave pública. | ||
| * @returns {Buffer} La clave pública leída desde el archivo. | ||
| * @throws {Error} Si ocurre un error al leer el archivo. | ||
| */ | ||
| static loadPublicKey(filePath) { | ||
| try { | ||
| const pemPublicKey = fs.readFileSync(filePath, 'utf8'); | ||
| const publicKey = crypto.createPublicKey(pemPublicKey); | ||
| return publicKey; | ||
| } catch (error) { | ||
| throw new Error("Error al cargar la clave pública: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Guarda una clave privada en un archivo. | ||
| * | ||
| * @param {Buffer} privateKey La clave privada que se quiere guardar. | ||
| * @param {string} filePath La ruta del archivo donde se guardará la clave. | ||
| * @throws {Error} Si ocurre un error al escribir en el archivo. | ||
| */ | ||
| static savePrivateKey(privateKey, filePath) { | ||
| try { | ||
| const pemPrivateKey = privateKey.export({ type: 'pkcs8', format: 'pem' }); | ||
| fs.writeFileSync(filePath, pemPrivateKey); | ||
| } catch (error) { | ||
| throw new Error("Error al guardar la clave privada: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Carga una clave privada desde un archivo. | ||
| * | ||
| * @param {string} filePath La ruta del archivo donde se encuentra la clave privada. | ||
| * @returns {Buffer} La clave privada leída desde el archivo. | ||
| * @throws {Error} Si ocurre un error al leer el archivo. | ||
| */ | ||
| static loadPrivateKey(filePath) { | ||
| try { | ||
| const pemPrivateKey = fs.readFileSync(filePath, 'utf8'); | ||
| const privateKey = crypto.createPrivateKey(pemPrivateKey); | ||
| return privateKey; | ||
| } catch (error) { | ||
| throw new Error("Error al cargar la clave privada: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Encripta un mensaje utilizando la clave pública (RSA). | ||
| * | ||
| * @param {string} data El mensaje que se desea encriptar (en texto plano). | ||
| * @param {Buffer} publicKey La clave pública utilizada para encriptar el mensaje. | ||
| * @returns {Buffer} El mensaje encriptado como un Buffer. | ||
| * @throws {Error} Si ocurre un error durante la encriptación. | ||
| */ | ||
| static encryptWithPublicKey(data, publicKey) { | ||
| try { | ||
| // Cifra el mensaje con la clave pública usando RSA y OAEP | ||
| return crypto.publicEncrypt({ | ||
| key: publicKey, | ||
| padding: crypto.constants.RSA_PKCS1_OAEP_PADDING | ||
| }, Buffer.from(data)); | ||
| } catch (error) { | ||
| throw new Error("Error al encriptar con la clave pública: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Desencripta un mensaje utilizando la clave privada (RSA). | ||
| * | ||
| * @param {Buffer} encryptedData Los datos encriptados que se desean desencriptar. | ||
| * @param {Buffer} privateKey La clave privada utilizada para desencriptar el mensaje. | ||
| * @returns {string} El mensaje desencriptado en texto plano. | ||
| * @throws {Error} Si ocurre un error durante la desencriptación. | ||
| */ | ||
| static decryptWithPrivateKey(encryptedData, privateKey) { | ||
| try { | ||
| // Desencripta los datos con la clave privada usando RSA y OAEP | ||
| const decrypted = crypto.privateDecrypt({ | ||
| key: privateKey, | ||
| padding: crypto.constants.RSA_PKCS1_OAEP_PADDING | ||
| }, encryptedData); | ||
| return decrypted.toString(); // Devuelve el mensaje original como cadena | ||
| } catch (error) { | ||
| throw new Error("Error al desencriptar con la clave privada: " + error.message); | ||
| } | ||
| } | ||
| } | ||
| module.exports = AsimetricUtils; |
-193
| const Encryptor = require('../src/Encryptor'); | ||
| const Decryptor = require('../src/Decryptor'); | ||
| const HashingUtils = require('../src/HashingUtils'); | ||
| const KeyGenerator = require('../src/KeyGenerator'); | ||
| const SecurityUtils = require('../src/SecurityUtils'); | ||
| const AsimetricUtils = require('../src/AsimetricUtils'); | ||
| // Clase Cryptix que ofrece operaciones de criptografía | ||
| class Cryptix { | ||
| // Métodos de Encriptación y Desencriptación | ||
| /** | ||
| * Encripta un texto plano utilizando un password y AES-GCM. | ||
| * @param {string} plainText - El texto que se desea encriptar. | ||
| * @param {string} password - La contraseña utilizada para la encriptación. | ||
| * @return {string} El texto encriptado en formato Base64. | ||
| */ | ||
| static async encrypt(plainText, password) { | ||
| return await Encryptor.encrypt(plainText, password); | ||
| } | ||
| /** | ||
| * Desencripta un texto previamente encriptado utilizando un password y AES-GCM. | ||
| * @param {string} encryptedText - El texto encriptado que se desea desencriptar. | ||
| * @param {string} password - La contraseña utilizada para la desencriptación. | ||
| * @return {string} El texto desencriptado. | ||
| */ | ||
| static async decrypt(encryptedText, password) { | ||
| return await Decryptor.decrypt(encryptedText, password); | ||
| } | ||
| // Métodos de Hashing | ||
| /** | ||
| * Genera un hash SHA-512 del texto proporcionado. | ||
| * @param {string} input - El texto plano para el cual se genera el hash. | ||
| * @return {string} El hash SHA-512 generado en formato Base64. | ||
| */ | ||
| static async generateSHA512Hash(input) { | ||
| return await HashingUtils.generateSecureHashSHA512(input); | ||
| } | ||
| /** | ||
| * Genera un hash SHA-256 del texto proporcionado. | ||
| * @param {string} input - El texto plano para el cual se genera el hash. | ||
| * @return {string} El hash SHA-256 generado en formato Base64. | ||
| */ | ||
| static async generateSHA256Hash(input) { | ||
| return await HashingUtils.generateSecureHashSHA256(input); | ||
| } | ||
| /** | ||
| * Verifica si el texto proporcionado corresponde al hash dado con SHA-512. | ||
| * @param {string} hash - El hash previamente generado. | ||
| * @param {string} textPlain - El texto plano que se desea verificar. | ||
| * @return {boolean} true si el texto corresponde al hash, false en caso contrario. | ||
| */ | ||
| static async hash512IsValid(hash, textPlain) { | ||
| return await HashingUtils.verifyHashSHA512(textPlain, hash); | ||
| } | ||
| /** | ||
| * Verifica si el texto proporcionado corresponde al hash dado con SHA-256. | ||
| * @param {string} hash - El hash previamente generado. | ||
| * @param {string} textPlain - El texto plano que se desea verificar. | ||
| * @return {boolean} true si el texto corresponde al hash, false en caso contrario. | ||
| */ | ||
| static async hash256IsValid(hash, textPlain) { | ||
| return await HashingUtils.verifyHashSHA256(textPlain, hash); | ||
| } | ||
| // Métodos de Generación de Claves y Sal | ||
| /** | ||
| * Genera una clave secreta a partir de una contraseña y un salt utilizando un algoritmo derivado. | ||
| * @param {string} password - La contraseña utilizada para generar la clave. | ||
| * @param {Buffer} salt - El salt utilizado en la generación de la clave. | ||
| * @return {Promise<Buffer>} La clave generada. | ||
| */ | ||
| static async generateKey(password, salt) { | ||
| return await KeyGenerator.generateKey(password, salt); | ||
| } | ||
| /** | ||
| * Genera un salt aleatorio para ser utilizado en la encriptación o hashing. | ||
| * @return {Buffer} Un array de bytes que representa un salt aleatorio. | ||
| */ | ||
| static generateSalt() { | ||
| return KeyGenerator.generateSalt(); | ||
| } | ||
| // Métodos de HMAC (Hashed Message Authentication Code) | ||
| /** | ||
| * Genera un HMAC utilizando HmacSHA512. | ||
| * @param {string} message - El mensaje que se va a autenticar. | ||
| * @param {string} secretKey - La clave secreta utilizada para generar el HMAC. | ||
| * @return {string} El HMAC generado en formato Base64. | ||
| */ | ||
| static generateHMAC(message, secretKey) { | ||
| return SecurityUtils.generateHMAC(message, secretKey); | ||
| } | ||
| /** | ||
| * Verifica si un HMAC recibido coincide con el HMAC generado a partir del mensaje y la clave secreta. | ||
| * @param {string} message - El mensaje original. | ||
| * @param {string} secretKey - La clave secreta utilizada. | ||
| * @param {string} receivedHMAC - El HMAC recibido que se desea verificar. | ||
| * @return {boolean} true si el HMAC coincide, de lo contrario false. | ||
| */ | ||
| static verifyHMAC(message, secretKey, receivedHMAC) { | ||
| return SecurityUtils.verifyHMAC(message, secretKey, receivedHMAC); | ||
| } | ||
| /** | ||
| * Genera una clave secreta aleatoria en Base64 para su uso en HMAC. | ||
| * @return {string} Clave secreta aleatoria en formato Base64. | ||
| */ | ||
| static generateRandomKey() { | ||
| return SecurityUtils.generateRandomKey(); | ||
| } | ||
| // Métodos de Encriptación Asimétrica | ||
| /** | ||
| * Genera un par de claves pública y privada utilizando RSA. | ||
| * @param {number} keySize - El tamaño de la clave en bits (por ejemplo, 2048). | ||
| * @return {Promise<KeyPair>} Un par de claves RSA (pública y privada). | ||
| */ | ||
| static async generateRSAKeyPair(keySize) { | ||
| return await AsimetricUtils.generateRSAKeyPair(keySize); | ||
| } | ||
| /** | ||
| * Encripta datos utilizando la clave pública RSA. | ||
| * @param {string} data - El texto plano que se desea encriptar. | ||
| * @param {PublicKey} publicKey - La clave pública utilizada para la encriptación. | ||
| * @return {Promise<Buffer>} Los datos encriptados. | ||
| */ | ||
| static async encryptWithPublicKey(data, publicKey) { | ||
| return await AsimetricUtils.encryptWithPublicKey(data, publicKey); | ||
| } | ||
| /** | ||
| * Desencripta datos utilizando la clave privada RSA. | ||
| * @param {Buffer} encryptedData - Los datos encriptados que se desean desencriptar. | ||
| * @param {PrivateKey} privateKey - La clave privada utilizada para la desencriptación. | ||
| * @return {Promise<string>} El texto desencriptado. | ||
| */ | ||
| static async decryptWithPrivateKey(encryptedData, privateKey) { | ||
| return await AsimetricUtils.decryptWithPrivateKey(encryptedData, privateKey); | ||
| } | ||
| // Métodos de Guardado y Carga de Claves | ||
| /** | ||
| * Guarda la clave pública en un archivo. | ||
| * @param {PublicKey} publicKey - La clave pública que se desea guardar. | ||
| * @param {string} filePath - La ruta del archivo donde se guardará la clave pública. | ||
| */ | ||
| static async savePublicKey(publicKey, filePath) { | ||
| return await AsimetricUtils.savePublicKey(publicKey, filePath); | ||
| } | ||
| /** | ||
| * Carga la clave pública desde un archivo. | ||
| * @param {string} filePath - La ruta del archivo desde donde se cargará la clave pública. | ||
| * @return {Promise<PublicKey>} La clave pública cargada. | ||
| */ | ||
| static async loadPublicKey(filePath) { | ||
| return await AsimetricUtils.loadPublicKey(filePath); | ||
| } | ||
| /** | ||
| * Guarda la clave privada en un archivo. | ||
| * @param {PrivateKey} privateKey - La clave privada que se desea guardar. | ||
| * @param {string} filePath - La ruta del archivo donde se guardará la clave privada. | ||
| */ | ||
| static async savePrivateKey(privateKey, filePath) { | ||
| return await AsimetricUtils.savePrivateKey(privateKey, filePath); | ||
| } | ||
| /** | ||
| * Carga la clave privada desde un archivo. | ||
| * @param {string} filePath - La ruta del archivo desde donde se cargará la clave privada. | ||
| * @return {Promise<PrivateKey>} La clave privada cargada. | ||
| */ | ||
| static async loadPrivateKey(filePath) { | ||
| return await AsimetricUtils.loadPrivateKey(filePath); | ||
| } | ||
| } | ||
| module.exports = Cryptix; |
| const crypto = require("crypto"); | ||
| class Decryptor { | ||
| // Parámetros de seguridad | ||
| static ITERATIONS = 10000; // Número de iteraciones para PBKDF2 | ||
| static SALT_LENGTH = 16; // Tamaño del salt en bytes (16 bytes) | ||
| static KEY_LENGTH = 32; // Longitud de la clave (256 bits → 32 bytes) | ||
| static IV_LENGTH = 12; // Longitud del IV para GCM (12 bytes) | ||
| static AUTH_TAG_LENGTH = 16; // Longitud del Auth Tag (16 bytes) | ||
| /** | ||
| * Desencripta un texto cifrado con AES-GCM usando una clave derivada con PBKDF2. | ||
| * @param {string} encryptedText - Texto cifrado en Base64 (salt + IV + cipherText + authTag). | ||
| * @param {string} password - Contraseña para derivar la clave. | ||
| * @returns {string} - Texto desencriptado. | ||
| */ | ||
| static decrypt(encryptedText, password) { | ||
| try { | ||
| // 1️⃣ Convertir el texto cifrado desde Base64 a Buffer | ||
| const encryptedData = Buffer.from(encryptedText, "base64"); | ||
| // 2️⃣ Extraer salt, IV, texto cifrado y Auth Tag | ||
| const salt = encryptedData.subarray(0, Decryptor.SALT_LENGTH); | ||
| const iv = encryptedData.subarray(Decryptor.SALT_LENGTH, Decryptor.SALT_LENGTH + Decryptor.IV_LENGTH); | ||
| const cipherText = encryptedData.subarray(Decryptor.SALT_LENGTH + Decryptor.IV_LENGTH, encryptedData.length - Decryptor.AUTH_TAG_LENGTH); | ||
| const authTag = encryptedData.subarray(encryptedData.length - Decryptor.AUTH_TAG_LENGTH); | ||
| // 3️⃣ Derivar la clave con PBKDF2 | ||
| const key = crypto.pbkdf2Sync(password, salt, Decryptor.ITERATIONS, Decryptor.KEY_LENGTH, "sha256"); | ||
| // 4️⃣ Crear el descifrador AES-GCM | ||
| const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv); | ||
| decipher.setAuthTag(authTag); | ||
| // 5️⃣ Desencriptar el texto | ||
| let decryptedText = decipher.update(cipherText); | ||
| decryptedText = Buffer.concat([decryptedText, decipher.final()]); | ||
| // Mostrar los detalles del desencriptado | ||
| console.log("Texto desencriptado: ", decryptedText.toString()); // Depuración | ||
| // 6️⃣ Convertir a string UTF-8 | ||
| return decryptedText.toString("utf8"); | ||
| } catch (error) { | ||
| throw new Error("Error al desencriptar el texto: " + error.message); | ||
| } | ||
| } | ||
| } | ||
| module.exports = Decryptor; |
| const fs = require('fs'); | ||
| const crypto = require('crypto'); | ||
| const Encryptor = require('./Encryptor'); // Asegúrate de que el Encryptor esté configurado | ||
| /** | ||
| * Clase encargada de cifrar archivos utilizando una clave secreta fija y una clave aleatoria generada | ||
| * dinámicamente para cada archivo. Aplica técnicas de ofuscación para aumentar la seguridad. | ||
| */ | ||
| class EncryptFile { | ||
| /** | ||
| * Clave secreta fija utilizada para cifrar la clave aleatoria del archivo. | ||
| * Esta clave debe mantenerse segura y nunca exponerse públicamente. | ||
| */ | ||
| static FIXED_SECRET = "mfl+dLeVbxTXFl9B1hb4+0AI4CLYh+LNnP9lMT0d0bcV8Hp0H2rOIsvg9RSPA/9L4V9TWaOJnZYEMyTbrsXKhg=="; | ||
| /** | ||
| * Cifra un archivo de texto plano y lo guarda en una nueva ubicación con formato ofuscado. | ||
| * | ||
| * @param {string} inputDecPath Ruta del archivo de entrada en texto plano (sin cifrar). | ||
| * @param {string} outputEncPath Ruta del archivo de salida cifrado. | ||
| * @throws {Error} En caso de error al leer/escribir archivos o durante el proceso de cifrado. | ||
| */ | ||
| static encryptFile(inputDecPath, outputEncPath) { | ||
| try { | ||
| // Leer el contenido del archivo original | ||
| const content = fs.readFileSync(inputDecPath, 'utf-8'); | ||
| // Generar una clave aleatoria de 256 bits para este archivo | ||
| const randomKey = crypto.randomBytes(32); | ||
| const encryptionKey = randomKey.toString('base64'); | ||
| // Cifrar la clave generada utilizando la clave secreta fija | ||
| const encryptedKey = Encryptor.encrypt(encryptionKey, EncryptFile.FIXED_SECRET); | ||
| // Cifrar el contenido del archivo utilizando la clave aleatoria generada | ||
| const encryptedContent = Encryptor.encrypt(content, encryptionKey); | ||
| // Generar un prefijo aleatorio de 32 bytes para ofuscar el contenido | ||
| const randomPrefix = crypto.randomBytes(32); | ||
| // Generar un sufijo aleatorio de 32 bytes para aumentar la seguridad | ||
| const randomSuffix = crypto.randomBytes(32); | ||
| // Crear la estructura del archivo cifrado con datos ofuscados | ||
| const formattedContent = | ||
| `0x3F8AD1B2: ${randomPrefix.toString('base64')}\n` + | ||
| `${randomPrefix.toString('base64')}\n` + | ||
| `${randomSuffix.toString('base64')}\n` + | ||
| "==== START ENCRYPTED DATA ====\n" + | ||
| encryptedKey + "\n" + // Clave cifrada | ||
| encryptedContent + "\n" + // Contenido cifrado | ||
| "==== END ENCRYPTED DATA ====\n" + | ||
| `0xFA34F9CD: ${randomSuffix.toString('base64')}\n`; | ||
| // Guardar el archivo cifrado en la ruta especificada | ||
| fs.writeFileSync(outputEncPath, formattedContent, 'utf-8'); | ||
| } catch (err) { | ||
| throw new Error(`Error al cifrar el archivo: ${err.message}`); | ||
| } | ||
| } | ||
| } | ||
| module.exports = EncryptFile; |
| const crypto = require("crypto"); | ||
| class Encryptor { | ||
| // Parámetros de seguridad | ||
| static ITERATIONS = 10000; // Número de iteraciones para PBKDF2 | ||
| static SALT_LENGTH = 16; // Tamaño del salt en bytes (16 bytes) | ||
| static KEY_LENGTH = 32; // Longitud de la clave (256 bits → 32 bytes) | ||
| static IV_LENGTH = 12; // Longitud del IV para GCM (12 bytes) | ||
| static AUTH_TAG_LENGTH = 16; // Longitud del Auth Tag (16 bytes) | ||
| /** | ||
| * Cifra un texto con AES-GCM usando una clave derivada con PBKDF2. | ||
| * @param {string} plainText - Texto a cifrar. | ||
| * @param {string} password - Contraseña para derivar la clave. | ||
| * @returns {string} - Texto cifrado en Base64 (salt + IV + cipherText + authTag). | ||
| */ | ||
| static encrypt(plainText, password) { | ||
| // 1️⃣ Generar un salt aleatorio | ||
| const salt = crypto.randomBytes(this.SALT_LENGTH); | ||
| // 2️⃣ Derivar la clave con PBKDF2 | ||
| const key = crypto.pbkdf2Sync(password, salt, this.ITERATIONS, this.KEY_LENGTH, "sha256"); | ||
| // 3️⃣ Generar un IV aleatorio | ||
| const iv = crypto.randomBytes(this.IV_LENGTH); | ||
| // 4️⃣ Crear el cifrador AES-GCM | ||
| const cipher = crypto.createCipheriv("aes-256-gcm", key, iv); | ||
| // 5️⃣ Cifrar el texto | ||
| let cipherText = cipher.update(plainText, "utf8"); | ||
| cipherText = Buffer.concat([cipherText, cipher.final()]); | ||
| // 6️⃣ Obtener el Auth Tag (16 bytes) | ||
| const authTag = cipher.getAuthTag(); | ||
| // 7️⃣ Concatenar (salt + iv + cipherText + authTag) | ||
| const encryptedData = Buffer.concat([salt, iv, cipherText, authTag]); | ||
| // 8️⃣ Devolver el resultado en Base64 | ||
| return encryptedData.toString("base64"); | ||
| } | ||
| } | ||
| module.exports = Encryptor; |
| const crypto = require('crypto'); | ||
| /** | ||
| * Clase segura para hashing con PBKDF2, SHA-512, SHA-256, salt aleatorio y un pepper secreto. | ||
| */ | ||
| class HashingUtils { | ||
| // Parámetros de seguridad | ||
| static PEPPER = Buffer.from("SuperSecretPepperKey12345!"); // Pepper secreto | ||
| static ITERATIONS = 10000; // Aumentado para mayor seguridad | ||
| static SALT_LENGTH = 64; // 64 bytes para mayor aleatoriedad | ||
| static HASH_LENGTH_512 = 64; // 512 bits (64 bytes) para SHA-512 | ||
| static HASH_LENGTH_256 = 32; // 256 bits (32 bytes) para SHA-256 | ||
| /** | ||
| * Genera un hash seguro usando PBKDF2 con HMAC-SHA-512, salt aleatorio y un pepper secreto. | ||
| * | ||
| * @param {string} input El texto plano que se va a hashear. | ||
| * @returns {string} Cadena en formato Base64 con el salt y el hash concatenados y separados por '$'. | ||
| */ | ||
| static generateSecureHashSHA512(input) { | ||
| try { | ||
| const salt = HashingUtils.generateSalt(); | ||
| const hash = HashingUtils.deriveKey(input, salt, true); // Usando SHA-512 | ||
| return HashingUtils.encodeBase64(salt) + "$" + HashingUtils.encodeBase64(hash); | ||
| } catch (e) { | ||
| throw new Error("Error al generar el hash seguro con SHA-512: " + e); | ||
| } | ||
| } | ||
| /** | ||
| * Genera un hash seguro usando PBKDF2 con HMAC-SHA-256, salt aleatorio y un pepper secreto. | ||
| * | ||
| * @param {string} input El texto plano que se va a hashear. | ||
| * @returns {string} Cadena en formato Base64 con el salt y el hash concatenados y separados por '$'. | ||
| */ | ||
| static generateSecureHashSHA256(input) { | ||
| try { | ||
| const salt = HashingUtils.generateSalt(); | ||
| const hash = HashingUtils.deriveKey(input, salt, false); // Usando SHA-256 | ||
| return HashingUtils.encodeBase64(salt) + "$" + HashingUtils.encodeBase64(hash); | ||
| } catch (e) { | ||
| throw new Error("Error al generar el hash seguro con SHA-256: " + e); | ||
| } | ||
| } | ||
| /** | ||
| * Verifica si un hash corresponde al texto plano dado usando SHA-512. | ||
| * | ||
| * @param {string} input El texto plano a verificar. | ||
| * @param {string} storedHashWithSalt El hash almacenado (salt$hash en Base64). | ||
| * @returns {boolean} true si el hash generado coincide con el almacenado; de lo contrario, false. | ||
| */ | ||
| static verifyHashSHA512(input, storedHashWithSalt) { | ||
| try { | ||
| const [storedSaltBase64, storedHashBase64] = storedHashWithSalt.split('$'); | ||
| const storedSalt = HashingUtils.decodeBase64(storedSaltBase64); | ||
| const storedHash = HashingUtils.decodeBase64(storedHashBase64); | ||
| const computedHash = HashingUtils.deriveKey(input, storedSalt, true); // Usando SHA-512 | ||
| return crypto.timingSafeEqual(storedHash, computedHash); | ||
| } catch (e) { | ||
| return false; | ||
| } | ||
| } | ||
| /** | ||
| * Verifica si un hash corresponde al texto plano dado usando SHA-256. | ||
| * | ||
| * @param {string} input El texto plano a verificar. | ||
| * @param {string} storedHashWithSalt El hash almacenado (salt$hash en Base64). | ||
| * @returns {boolean} true si el hash generado coincide con el almacenado; de lo contrario, false. | ||
| */ | ||
| static verifyHashSHA256(input, storedHashWithSalt) { | ||
| try { | ||
| const [storedSaltBase64, storedHashBase64] = storedHashWithSalt.split('$'); | ||
| const storedSalt = HashingUtils.decodeBase64(storedSaltBase64); | ||
| const storedHash = HashingUtils.decodeBase64(storedHashBase64); | ||
| const computedHash = HashingUtils.deriveKey(input, storedSalt, false); // Usando SHA-256 | ||
| return crypto.timingSafeEqual(storedHash, computedHash); | ||
| } catch (e) { | ||
| return false; | ||
| } | ||
| } | ||
| /** | ||
| * Deriva una clave usando PBKDF2 con HMAC-SHA-512 o HMAC-SHA-256 y un pepper. | ||
| * | ||
| * @param {string} input Texto plano a convertir en hash. | ||
| * @param {Buffer} salt Salt aleatorio utilizado en el hashing. | ||
| * @param {boolean} useSHA512 Si es verdadero, usa SHA-512, de lo contrario usa SHA-256. | ||
| * @returns {Buffer} Array de bytes con el hash derivado. | ||
| */ | ||
| static deriveKey(input, salt, useSHA512) { | ||
| const algorithm = useSHA512 ? 'sha512' : 'sha256'; | ||
| const hashLength = useSHA512 ? HashingUtils.HASH_LENGTH_512 : HashingUtils.HASH_LENGTH_256; | ||
| const pepperedInput = input + HashingUtils.PEPPER.toString('utf8'); // Agregar pepper | ||
| return crypto.pbkdf2Sync(pepperedInput, salt, HashingUtils.ITERATIONS, hashLength, algorithm); | ||
| } | ||
| /** | ||
| * Convierte un array de bytes en una cadena Base64. | ||
| * | ||
| * @param {Buffer} data Datos en bytes. | ||
| * @returns {string} Cadena codificada en Base64. | ||
| */ | ||
| static encodeBase64(data) { | ||
| return data.toString('base64'); | ||
| } | ||
| /** | ||
| * Decodifica una cadena Base64 en un array de bytes. | ||
| * | ||
| * @param {string} base64 Cadena en Base64. | ||
| * @returns {Buffer} Array de bytes decodificado. | ||
| */ | ||
| static decodeBase64(base64) { | ||
| return Buffer.from(base64, 'base64'); | ||
| } | ||
| /** | ||
| * Genera un salt aleatorio de longitud fija. | ||
| * | ||
| * @returns {Buffer} Un buffer con un salt aleatorio. | ||
| */ | ||
| static generateSalt() { | ||
| return crypto.randomBytes(HashingUtils.SALT_LENGTH); | ||
| } | ||
| } | ||
| module.exports = HashingUtils; |
| const crypto = require('crypto'); | ||
| /** | ||
| * Clase KeyGenerator que proporciona métodos para generar claves seguras | ||
| * a partir de contraseñas y sal (salt), utilizando algoritmos criptográficos robustos. | ||
| */ | ||
| class KeyGenerator { | ||
| // Constantes de seguridad | ||
| static SALT_LENGTH = 16; // 16 bytes de sal | ||
| static ITERATIONS = 20000; // 20,000 iteraciones para PBKDF2 | ||
| static KEY_LENGTH = 32; // Longitud de clave de 256 bits (32 bytes) | ||
| /** | ||
| * Genera una clave secreta AES a partir de una contraseña y un salt utilizando PBKDF2. | ||
| * Este proceso deriva una clave segura a partir de una contraseña utilizando el salt y el algoritmo PBKDF2. | ||
| * | ||
| * @param {string} password La contraseña que se utilizará para generar la clave. | ||
| * @param {Buffer} salt El salt aleatorio utilizado para derivar la clave. | ||
| * @returns {Buffer} La clave generada para AES. | ||
| */ | ||
| static generateKey(password, salt) { | ||
| // Usamos PBKDF2 con SHA-512 para generar una clave más robusta | ||
| return new Promise((resolve, reject) => { | ||
| crypto.pbkdf2(password, salt, KeyGenerator.ITERATIONS, KeyGenerator.KEY_LENGTH, 'sha512', (err, derivedKey) => { | ||
| if (err) reject(err); | ||
| resolve(derivedKey); // La clave derivada de 256 bits | ||
| }); | ||
| }); | ||
| } | ||
| /** | ||
| * Genera un salt aleatorio de longitud fija utilizando crypto.randomBytes. | ||
| * El salt se utiliza para diversificar los resultados de la función de derivación de claves. | ||
| * | ||
| * @returns {Buffer} Un buffer con un salt aleatorio. | ||
| */ | ||
| static generateSalt() { | ||
| return crypto.randomBytes(KeyGenerator.SALT_LENGTH); | ||
| } | ||
| /** | ||
| * Genera una contraseña segura de la longitud especificada. | ||
| * <p> | ||
| * Este método utiliza un generador de números aleatorios criptográficamente seguro | ||
| * ({@link crypto.randomBytes}) para crear una contraseña aleatoria con caracteres | ||
| * alfanuméricos y especiales. La contraseña generada es adecuada para su uso en | ||
| * autenticación y almacenamiento seguro. | ||
| * </p> | ||
| * | ||
| * @param {number} length La longitud de la contraseña generada. Debe ser un número positivo mayor a 0. | ||
| * @returns {string} Una contraseña segura generada aleatoriamente. | ||
| * @throws {Error} Si la longitud especificada es menor o igual a 0. | ||
| */ | ||
| static generateSecurePassword(length) { | ||
| if (length <= 0) { | ||
| throw new Error("La longitud de la contraseña debe ser mayor que 0."); | ||
| } | ||
| const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+"; | ||
| const randomBytes = crypto.randomBytes(length); | ||
| let password = ''; | ||
| // Generar la contraseña aleatoria | ||
| for (let i = 0; i < length; i++) { | ||
| password += characters.charAt(randomBytes[i] % characters.length); | ||
| } | ||
| return password; | ||
| } | ||
| } | ||
| module.exports = KeyGenerator; |
| const fs = require('fs'); | ||
| const crypto = require('crypto'); | ||
| // Clave interna fija | ||
| const FIXED_SECRET = "mfl+dLeVbxTXFl9B1hb4+0AI4CLYh+LNnP9lMT0d0bcV8Hp0H2rOIsvg9RSPA/9L4V9TWaOJnZYEMyTbrsXKhg=="; | ||
| let decryptedContent = null; // Contenido desencriptado | ||
| let keyValueMap = {}; // Almacén de claves en memoria | ||
| /** | ||
| * Inicializa la clase cargando y desencriptando el contenido del archivo cifrado. | ||
| * @param {string} encFilePath Ruta del archivo .enc | ||
| * @throws {Error} Si ocurre un error al leer o desencriptar el archivo | ||
| */ | ||
| async function init(encFilePath) { | ||
| const encryptedFileContent = fs.readFileSync(encFilePath, { encoding: 'utf8' }); | ||
| // Extraer y desencriptar clave y contenido | ||
| const encryptedKey = extractEncryptedKey(encryptedFileContent); | ||
| const encryptedData = extractEncryptedData(encryptedFileContent); | ||
| if (!encryptedKey || !encryptedData) { | ||
| throw new Error("Clave cifrada o contenido no encontrados en el archivo."); | ||
| } | ||
| const encryptionKey = decrypt(encryptedKey, FIXED_SECRET); | ||
| decryptedContent = decrypt(encryptedData, encryptionKey); | ||
| // Cargar el contenido en memoria para mejorar rendimiento | ||
| parseDecryptedContent(); | ||
| } | ||
| /** | ||
| * Parsea el contenido desencriptado y lo almacena en un mapa clave-valor. | ||
| */ | ||
| function parseDecryptedContent() { | ||
| keyValueMap = {}; | ||
| decryptedContent.split("\n").forEach(line => { | ||
| if (line.startsWith("| ") && line.includes("->")) { | ||
| const parts = line.split("->"); | ||
| if (parts.length === 2) { | ||
| const key = parts[0].replace("|", "").trim(); | ||
| const value = parts[1].trim(); | ||
| keyValueMap[key] = value; | ||
| } | ||
| } | ||
| }); | ||
| } | ||
| /** | ||
| * Desencripta un texto cifrado con AES-GCM usando una clave derivada con PBKDF2. | ||
| * @param {string} encryptedText Texto cifrado en Base64. | ||
| * @param {string} password Contraseña para derivar la clave. | ||
| * @returns {string} Texto desencriptado. | ||
| */ | ||
| function decrypt(encryptedText, password) { | ||
| try { | ||
| // Convertir el texto cifrado desde Base64 a Buffer | ||
| const encryptedData = Buffer.from(encryptedText, 'base64'); | ||
| // Extraer salt, IV, texto cifrado y Auth Tag | ||
| const salt = encryptedData.slice(0, 16); | ||
| const iv = encryptedData.slice(16, 28); | ||
| const cipherText = encryptedData.slice(28, encryptedData.length - 16); | ||
| const authTag = encryptedData.slice(encryptedData.length - 16); | ||
| // Derivar la clave con PBKDF2 | ||
| const key = crypto.pbkdf2Sync(password, salt, 10000, 32, 'sha256'); | ||
| // Crear el descifrador AES-GCM | ||
| const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); | ||
| decipher.setAuthTag(authTag); | ||
| // Desencriptar el texto | ||
| let decryptedText = decipher.update(cipherText); | ||
| decryptedText = Buffer.concat([decryptedText, decipher.final()]); | ||
| return decryptedText.toString('utf8'); | ||
| } catch (error) { | ||
| throw new Error("Error al desencriptar el texto: " + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Obtiene el valor de una clave como String. | ||
| * @param {string} keyName Nombre de la clave | ||
| * @returns {string} Valor asociado o null si no existe | ||
| */ | ||
| function getKey(keyName) { | ||
| return keyValueMap[keyName] || null; | ||
| } | ||
| /** | ||
| * Extrae la clave cifrada desde el contenido del archivo. | ||
| * @param {string} content Contenido del archivo cifrado | ||
| * @returns {string|null} La clave cifrada en Base64 | ||
| */ | ||
| function extractEncryptedKey(content) { | ||
| const startIndex = content.indexOf("==== START ENCRYPTED DATA ===="); | ||
| if (startIndex === -1) { | ||
| return null; | ||
| } | ||
| const endIndex = content.indexOf("\n", startIndex + "==== START ENCRYPTED DATA ====\n".length); | ||
| if (endIndex === -1) { | ||
| return null; | ||
| } | ||
| return content.substring(startIndex + "==== START ENCRYPTED DATA ====\n".length, endIndex).trim(); | ||
| } | ||
| /** | ||
| * Extrae los datos cifrados desde el contenido del archivo. | ||
| * @param {string} content Contenido del archivo cifrado | ||
| * @returns {string|null} Los datos cifrados en Base64 | ||
| */ | ||
| function extractEncryptedData(content) { | ||
| const startIndex = content.indexOf("==== START ENCRYPTED DATA ===="); | ||
| if (startIndex === -1) { | ||
| return null; | ||
| } | ||
| const firstLineEnd = content.indexOf("\n", startIndex + "==== START ENCRYPTED DATA ====\n".length); | ||
| if (firstLineEnd === -1) { | ||
| return null; | ||
| } | ||
| const dataStart = firstLineEnd + 1; | ||
| const endIndex = content.indexOf("==== END ENCRYPTED DATA ====", dataStart); | ||
| if (endIndex === -1) { | ||
| return null; | ||
| } | ||
| return content.substring(dataStart, endIndex).trim(); | ||
| } | ||
| module.exports = { init, getKey }; |
| const crypto = require('crypto'); | ||
| /** | ||
| * Clase SecurityUtils con funciones avanzadas de seguridad, | ||
| * incluyendo generación y verificación de HMAC con SHA-512, claves seguras y más. | ||
| */ | ||
| class SecurityUtils { | ||
| static HMAC_ALGORITHM = 'sha512'; | ||
| static PBKDF2_ITERATIONS = 150000; | ||
| static KEY_LENGTH = 64; // 512 bits para mayor seguridad | ||
| /** | ||
| * Genera un HMAC (Hashed Message Authentication Code) utilizando SHA-512 con una clave secreta segura. | ||
| * | ||
| * @param {string} message El mensaje que se va a autenticar. | ||
| * @param {string} secretKey La clave secreta utilizada para generar el HMAC. | ||
| * @returns {string} El HMAC generado en formato Base64. | ||
| */ | ||
| static generateHMAC(message, secretKey) { | ||
| try { | ||
| // Crear la instancia de HMAC-SHA-512 | ||
| const hmac = crypto.createHmac(SecurityUtils.HMAC_ALGORITHM, secretKey); | ||
| // Generar el HMAC para el mensaje | ||
| hmac.update(message); | ||
| const hmacBytes = hmac.digest(); | ||
| // Devolver el HMAC codificado en Base64 | ||
| return hmacBytes.toString('base64'); | ||
| } catch (error) { | ||
| throw new Error('Error al generar el HMAC: ' + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Verifica si un HMAC es válido comparándolo con un mensaje dado. | ||
| * | ||
| * @param {string} message El mensaje original. | ||
| * @param {string} secretKey La clave secreta utilizada para generar el HMAC. | ||
| * @param {string} receivedHMAC El HMAC recibido. | ||
| * @returns {boolean} {@code true} si el HMAC es válido, {@code false} en caso contrario. | ||
| */ | ||
| static verifyHMAC(message, secretKey, receivedHMAC) { | ||
| const computedHMAC = SecurityUtils.generateHMAC(message, secretKey); | ||
| return computedHMAC === receivedHMAC; | ||
| } | ||
| /** | ||
| * Genera una clave secreta segura utilizando PBKDF2 con HMAC-SHA-512. | ||
| * | ||
| * @param {string} password La contraseña base para derivar la clave. | ||
| * @param {Buffer} salt Un valor aleatorio para fortalecer la clave. | ||
| * @returns {string} Una clave secreta segura en formato Base64. | ||
| */ | ||
| static generateSecureKey(password, salt) { | ||
| try { | ||
| // Derivar la clave utilizando PBKDF2 | ||
| const key = crypto.pbkdf2Sync(password, salt, SecurityUtils.PBKDF2_ITERATIONS, SecurityUtils.KEY_LENGTH, 'sha512'); | ||
| // Devolver la clave codificada en Base64 | ||
| return key.toString('base64'); | ||
| } catch (error) { | ||
| throw new Error('Error al generar la clave segura: ' + error.message); | ||
| } | ||
| } | ||
| /** | ||
| * Genera una clave secreta aleatoria segura. | ||
| * | ||
| * @returns {string} Una clave secreta en formato Base64. | ||
| */ | ||
| static generateRandomKey() { | ||
| const key = crypto.randomBytes(64); // 512 bits (64 bytes) | ||
| return key.toString('base64'); | ||
| } | ||
| /** | ||
| * Genera un salt aleatorio seguro. | ||
| * | ||
| * @returns {Buffer} Un salt aleatorio en bytes. | ||
| */ | ||
| static generateSalt() { | ||
| return crypto.randomBytes(32); // 256 bits | ||
| } | ||
| } | ||
| module.exports = SecurityUtils; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
No tests
QualityPackage does not have any tests. This is a strong signal of a poorly maintained or low quality package.
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
159814
67.99%40
185.71%1642
105.51%706
33.71%1
-75%3
50%2
100%1
Infinity%