UNPKG

xypriss-security

Version:

XyPriss Security is an advanced JavaScript security library designed for enterprise applications. It provides military-grade encryption, secure data structures, quantum-resistant cryptography, and comprehensive security utilities for modern web applicatio

203 lines (199 loc) 8.11 kB
'use strict'; var keysTypes = require('./keys-types.js'); var keysLogger = require('./keys-logger.js'); var keysUtils = require('./keys-utils.js'); var Argon2Algo = require('./algorithms/mods/Argon2Algo.js'); var PBKDF2Algo = require('./algorithms/mods/PBKDF2Algo.js'); var ScryptAlgo = require('./algorithms/mods/ScryptAlgo.js'); var stats = require('../../utils/stats.js'); var randomCore = require('../random/random-core.js'); require('../random/random-types.js'); require('crypto'); var constants = require('../../utils/constants.js'); require('../random/random-sources.js'); require('nehonix-uri-processor'); require('../../utils/memory/index.js'); require('../../types.js'); require('../random/random-security.js'); /** * Key Derivation Core * Main orchestrator for the modular key derivation system */ /** * Optimized Keys class with modular architecture * Maintains backward compatibility while providing enhanced performance */ class OptimizedKeys { constructor() { this.environmentInfo = keysUtils.EnvironmentDetector.detect(); this.metricsCache = []; keysLogger.keyLogger.info("Core", "Optimized Keys system initialized", { environment: this.environmentInfo.type, capabilities: this.environmentInfo.capabilities, }); } /** * Get singleton instance */ static getInstance() { if (!OptimizedKeys.instance) { OptimizedKeys.instance = new OptimizedKeys(); } return OptimizedKeys.instance; } /** * Derive a key from a password or other input (backward compatible) * @param input - The input to derive a key from * @param options - Key derivation options * @returns The derived key as a hex string */ deriveKey(input, options = {}) { const result = this.deriveKeyExtended(input, options); return result.key; } /** * Derive a key with extended options and metadata * @param input - The input to derive a key from * @param options - Extended key derivation options * @returns Complete derivation result with metadata */ deriveKeyExtended(input, options = {}) { const startTime = Date.now(); // Validate and normalize inputs const algorithm = keysUtils.ValidationUtils.validateAlgorithm(options.algorithm || "pbkdf2"); const iterations = keysUtils.ValidationUtils.validateIterations(options.iterations || this.getDefaultIterations(algorithm)); const keyLength = keysUtils.ValidationUtils.validateKeyLength(options.keyLength || constants.SECURITY_DEFAULTS.KEY_LENGTH); const hashFunction = keysUtils.ValidationUtils.validateHashFunction(options.hashFunction || "sha256"); // Convert input to bytes const inputBytes = keysUtils.ConversionUtils.toUint8Array(input); // Generate or validate salt let saltBytes; if (options.salt) { saltBytes = keysUtils.ValidationUtils.validateSalt(options.salt); } else { saltBytes = randomCore.SecureRandom.getRandomBytes(16); } keysLogger.keyLogger.logAlgorithmSelection(algorithm, keysTypes.AlgorithmBackend.NODE_CRYPTO, // Will be updated by implementation "User specified or default selection"); // Derive the key using the appropriate algorithm let derivationResult; try { switch (algorithm) { case keysTypes.KeyDerivationAlgorithm.PBKDF2: derivationResult = PBKDF2Algo.PBKDF2Algo.derive(inputBytes, saltBytes, iterations, keyLength, hashFunction); break; case keysTypes.KeyDerivationAlgorithm.SCRYPT: const scryptCost = this.iterationsToScryptCost(iterations); derivationResult = ScryptAlgo.ScryptAlgo.derive(inputBytes, saltBytes, scryptCost, keyLength); break; case keysTypes.KeyDerivationAlgorithm.ARGON2: case keysTypes.KeyDerivationAlgorithm.ARGON2ID: derivationResult = Argon2Algo.Argon2Algo.derive(inputBytes, saltBytes, iterations, keyLength, "argon2id"); break; case keysTypes.KeyDerivationAlgorithm.ARGON2I: derivationResult = Argon2Algo.Argon2Algo.derive(inputBytes, saltBytes, iterations, keyLength, "argon2i"); break; case keysTypes.KeyDerivationAlgorithm.ARGON2D: derivationResult = Argon2Algo.Argon2Algo.derive(inputBytes, saltBytes, iterations, keyLength, "argon2d"); break; default: throw new Error(`Unsupported algorithm: ${algorithm}`); } } catch (error) { keysLogger.keyLogger.error("Core", "Key derivation failed", error); throw error; } // Convert result to hex const hexKey = keysUtils.ConversionUtils.toHexString(derivationResult.key); // Secure memory cleanup if (options.secureWipe !== false) { keysUtils.ConversionUtils.secureWipe(derivationResult.key); keysUtils.ConversionUtils.secureWipe(inputBytes); } // Track statistics const endTime = Date.now(); stats.StatsTracker.getInstance().trackKeyDerivation(endTime - startTime, keyLength * 8 // Entropy bits ); // Cache metrics this.metricsCache.push(derivationResult.metrics); if (this.metricsCache.length > 100) { this.metricsCache.shift(); // Keep only recent metrics } const result = { key: hexKey, algorithm, backend: derivationResult.backend, metrics: derivationResult.metrics, salt: saltBytes, iterations, }; keysLogger.keyLogger.info("Core", "Key derivation completed successfully", { algorithm, backend: derivationResult.backend, executionTime: `${derivationResult.metrics.executionTime}ms`, }); return result; } /** * Get default iterations for an algorithm */ getDefaultIterations(algorithm) { switch (algorithm) { case keysTypes.KeyDerivationAlgorithm.PBKDF2: return keysUtils.ALGORITHM_DEFAULTS.PBKDF2.iterations; case keysTypes.KeyDerivationAlgorithm.SCRYPT: return Math.pow(2, keysUtils.ALGORITHM_DEFAULTS.SCRYPT.cost); case keysTypes.KeyDerivationAlgorithm.ARGON2: case keysTypes.KeyDerivationAlgorithm.ARGON2ID: case keysTypes.KeyDerivationAlgorithm.ARGON2I: case keysTypes.KeyDerivationAlgorithm.ARGON2D: return keysUtils.ALGORITHM_DEFAULTS.ARGON2.timeCost; default: return constants.SECURITY_DEFAULTS.PBKDF2_ITERATIONS; } } /** * Convert iterations to scrypt cost parameter */ iterationsToScryptCost(iterations) { // Convert iterations to scrypt N parameter (power of 2) const cost = Math.log2(iterations); return Math.max(10, Math.min(20, Math.round(cost))); } /** * Get performance metrics */ getMetrics() { return this.metricsCache.slice(); } /** * Get environment information */ getEnvironmentInfo() { return this.environmentInfo; } /** * Clear metrics cache */ clearMetrics() { this.metricsCache.length = 0; } /** * Get algorithm recommendations based on environment */ getRecommendedAlgorithm() { if (this.environmentInfo.capabilities.argon2) { return keysTypes.KeyDerivationAlgorithm.ARGON2ID; } else if (this.environmentInfo.capabilities.scrypt) { return keysTypes.KeyDerivationAlgorithm.SCRYPT; } else { return keysTypes.KeyDerivationAlgorithm.PBKDF2; } } } exports.OptimizedKeys = OptimizedKeys; //# sourceMappingURL=keys-core.js.map