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
1,736 lines (1,712 loc) • 403 kB
TypeScript
import * as crypto from 'crypto';
import crypto__default from 'crypto';
import { EventEmitter } from 'events';
import { Request, Response } from 'express';
/**
* Type definitions for the XyPrissSecurity library
*/
type RateLimitMiddlewareOptions$1 = any;
/**
* Security level enum
*/
declare enum SecurityLevel$1 {
STANDARD = "standard",
HIGH = "high",
MAXIMUM = "maximum"
}
/**
* Token type enum
*/
declare enum TokenType {
GENERAL = "general",
API_KEY = "api_key",
SESSION = "session",
JWT = "jwt",
TOTP = "totp"
}
/**
* Hash algorithm enum - can be used as values
*/
declare enum HashAlgorithm$2 {
SHA256 = "sha256",
SHA512 = "sha512",
SHA3_256 = "sha3-256",
SHA3_512 = "sha3-512",
BLAKE3 = "blake3",
BLAKE2B = "blake2b",
BLAKE2S = "blake2s",
PBKDF2 = "pbkdf2"
}
/**
* Supported hash algorithms - accepts both string literals AND enum values
*
* Usage examples:
* - String literal: algorithm: "sha256"
* - Enum value: algorithm: HashAlgorithmEnum.SHA256
* - Both are type-safe and supported!
*/
type HashAlgorithmType = "sha256" | "sha512" | "sha3-256" | "sha3-512" | "blake3" | "blake2b" | "blake2s" | "pbkdf2";
/**
* Key derivation algorithm enum
*/
declare enum KeyDerivationAlgorithm {
PBKDF2 = "pbkdf2",
ARGON2 = "argon2",
BALLOON = "balloon"
}
/**
* Entropy source enum
*/
declare enum EntropySource {
SYSTEM = "system",
BROWSER = "browser",
USER = "user",
NETWORK = "network",
COMBINED = "combined",
CSPRNG = "csprng",
MATH_RANDOM = "math_random",
CUSTOM = "custom"
}
/**
* Secure token options
*/
interface SecureTokenOptions {
/**
* Length of the token
* @default 32
*/
length?: number;
/**
* Include uppercase letters
* @default true
*/
includeUppercase?: boolean;
/**
* Include lowercase letters
* @default true
*/
includeLowercase?: boolean;
/**
* Include numbers
* @default true
*/
includeNumbers?: boolean;
/**
* Include symbols
* @default false
*/
includeSymbols?: boolean;
/**
* Exclude similar characters (e.g., 1, l, I, 0, O)
* @default false
*/
excludeSimilarCharacters?: boolean;
/**
* Entropy level
* @default 'high'
*/
entropy: "high" | "maximum" | "standard";
maxValidityLength?: number;
}
/**
* Hash options
*/
interface HashOptions {
/**
* Salt for the hash
* If not provided, a random salt will be generated
*/
salt?: string | Uint8Array;
/**
* Pepper for the hash (secret server-side value)
*/
pepper?: string | Uint8Array;
/**
* Number of iterations
* @default 10000
*/
iterations?: number;
/**
* Hash algorithm
* @default 'sha256'
*/
algorithm?: HashAlgorithm$2 | HashAlgorithmType;
/**
* Output format ()
* @default 'hex'
*/
outputFormat?: EncodingHashType$1;
/**
* Output length in bytes
* @default 32
*/
outputLength?: number;
}
/**
* Key derivation options
*/
interface KeyDerivationOptions {
/**
* Salt for key derivation
* If not provided, a random salt will be generated
*/
salt?: string | Uint8Array;
/**
* Number of iterations
* @default 100000
*/
iterations?: number;
/**
* Key derivation algorithm
* @default 'pbkdf2'
*/
algorithm?: KeyDerivationAlgorithm | string;
/**
* Hash function to use (for PBKDF2)
* @default 'sha256'
*/
hashFunction?: HashAlgorithm$2 | string;
/**
* Output length in bytes
* @default 32
*/
keyLength?: number;
/**
* Memory cost for memory-hard functions (in KB)
* @default 65536 (64 MB)
*/
memoryCost?: number;
/**
* Parallelism factor for memory-hard functions
* @default 4
*/
parallelism?: number;
}
/**
* API key options
*/
interface APIKeyOptions {
/**
* Prefix for the API key
* @default ''
*/
prefix?: string;
/**
* Include timestamp in the API key
* @default true
*/
includeTimestamp?: boolean;
/**
* Length of the random part
* @default 32
*/
randomPartLength?: number;
/**
* Separator between parts
* @default '_'
*/
separator?: string;
/**
* Encoding type for the API key
*/
encoding?: EncodingHashType$1;
}
/**
* Session token options
*/
interface SessionTokenOptions {
/**
* User ID to include in the token
*/
userId?: string | number;
/**
* IP address to include in the token
*/
ipAddress?: string;
/**
* User agent to include in the token
*/
userAgent?: string;
/**
* Expiration time in seconds
* @default 3600 (1 hour)
*/
expiresIn?: number;
}
/**
* Middleware options
*/
interface MiddlewareOptions {
/**
* Custom headers to add to the response
* @default {}
*/
customHeaders?: Record<string, string>;
/**
* Callback function to handle rate limit exceeded
*/
onRateLimit?: (req: any, res: any) => void;
/**
* Callback function to handle CSRF errors
*/
onCSRFError?: (req: any, res: any) => void;
/**
* Callback function to handle errors
*/
onError?: (req: any, res: any) => void;
/**
* Callback function to handle metrics
*/
metricsHook?: (metrics: any) => void;
/**
* Enable CSRF protection
* @default false
*/
csrfProtection?: boolean;
/**
* Enable secure headers
* @default true
*/
secureHeaders?: boolean;
/**
* Enable rate limiting
* @default true
*/
rateLimit?: boolean | RateLimitMiddlewareOptions$1;
/**
* Maximum requests per minute
* @default 100
*/
maxRequestsPerMinute?: number;
/**
* Secret for token generation
* If not provided, a random secret will be generated (use Random.getRandomBytes)
*/
tokenSecret?: string;
/**
* Name of the CSRF cookie
* @default 'nehonix_xypriss_csrf'
*/
cookieName?: string;
/**
* Name of the CSRF header
* @default 'X-XyPriss_CSRF-Token'
*/
headerName?: string;
/**
* Paths to exclude from CSRF protection
* @default ['/api/health', '/api/status']
*/
excludePaths?: string[];
/**
* Whether to log requests
* @default true
*/
logRequests?: boolean;
/**
* Logger to use
* @default console
*/
logger?: Console;
/**
* Content Security Policy header value
* @default "default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'"
*/
contentSecurityPolicy?: string;
}
/**
* Crypto stats
*/
interface CryptoStats {
/**
* Number of tokens generated
*/
tokensGenerated: number;
/**
* Number of hashes computed
*/
hashesComputed: number;
/**
* Number of keys derived
*/
keysDerivated: number;
/**
* Average entropy in bits
*/
averageEntropyBits: number;
/**
* Timestamp of the last operation
*/
lastOperationTime: string;
/**
* Performance metrics
*/
performance: {
/**
* Average token generation time in milliseconds
*/
tokenGenerationAvgMs: number;
/**
* Average hash computation time in milliseconds
*/
hashComputationAvgMs: number;
/**
* Average key derivation time in milliseconds
*/
keyDerivationAvgMs: number;
};
/**
* Memory usage metrics
*/
memory: {
/**
* Average memory usage in bytes
*/
averageUsageBytes: number;
/**
* Peak memory usage in bytes
*/
peakUsageBytes: number;
};
}
/**
* Security test result
*/
interface SecurityTestResult {
/**
* Whether all tests passed
*/
passed: boolean;
/**
* Test results
*/
results: {
/**
* Random number generation test
*/
randomness: {
passed: boolean;
details: any;
};
/**
* Hash function test
*/
hashing: {
passed: boolean;
details: any;
};
/**
* Timing attack resistance test
*/
timingAttacks: {
passed: boolean;
details: any;
};
};
}
/**
* Password strength result
*/
interface PasswordStrengthResult {
/**
* Password strength score (0-100)
*/
score: number;
/**
* Feedback messages
*/
feedback: string[];
/**
* Estimated time to crack
*/
estimatedCrackTime: string;
/**
* Detailed analysis
*/
analysis: {
/**
* Length score
*/
length: number;
/**
* Entropy score
*/
entropy: number;
/**
* Character variety score
*/
variety: number;
/**
* Pattern penalty
*/
patterns: number;
};
}
interface EnhancedHashOptions extends HashOptions {
strength?: HashStrength;
memoryHard?: boolean;
quantumResistant?: boolean;
timingSafe?: boolean;
validateInput?: boolean;
secureWipe?: boolean;
}
type BaseEncodingType = "unicode" | "htmlEntity" | "punycode" | "asciihex" | "asciioct" | "rot13" | "base32" | "urlSafeBase64" | "jsEscape" | "cssEscape" | "utf7" | "quotedPrintable" | "decimalHtmlEntity";
type EncodingHashType$1 = "hex" | "base64" | "base64url" | "binary" | "utf8" | "buffer" | "base58" | BaseEncodingType;
interface SecureHashOptions {
algorithm?: string;
iterations?: number;
salt?: string | Buffer | Uint8Array;
pepper?: string | Buffer | Uint8Array;
outputFormat?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer";
keyDerivation?: "argon2" | "scrypt" | "pbkdf2" | "bcrypt";
parallelism?: number;
memorySize?: number;
timeCost?: number;
quantumResistant?: boolean;
domainSeparation?: string;
}
/**
* Hash types and interfaces
* Centralized type definitions for the hash module
*/
declare enum HashStrength {
WEAK = "WEAK",
FAIR = "FAIR",
GOOD = "GOOD",
STRONG = "STRONG",
MILITARY = "MILITARY"
}
type HashSecurityLevel = "LOW" | "MEDIUM" | "HIGH" | "MILITARY";
interface HashMonitoringResult {
securityLevel: HashSecurityLevel;
threats: string[];
recommendations: string[];
timestamp: number;
}
interface HashEntropyAnalysis {
shannonEntropy: number;
minEntropy: number;
compressionRatio: number;
randomnessScore: number;
qualityGrade: "POOR" | "FAIR" | "GOOD" | "EXCELLENT";
recommendations: string[];
}
interface HashAgilityResult {
hash: string | Buffer;
algorithm: string;
fallbacks: string[];
metadata: {
version: string;
timestamp: number;
strength: string;
};
}
interface HSMHashOptions {
keySlot?: number;
algorithm?: "sha256" | "sha512" | "sha3-256";
outputFormat?: "hex" | "base64" | "buffer";
validateIntegrity?: boolean;
}
interface SideChannelOptions {
constantTime?: boolean;
memoryProtection?: boolean;
powerAnalysisResistant?: boolean;
outputFormat?: "hex" | "base64" | "buffer";
}
interface HashConfiguration {
algorithm: string;
iterations: number;
saltLength: number;
keyLength: number;
memoryCost?: number;
timeCost?: number;
parallelism?: number;
}
interface StrengthConfiguration {
minIterations: number;
saltLength: number;
algorithm?: string;
memoryCost?: number;
timeCost?: number;
parallelism?: number;
hashLength?: number;
fallbackIterations?: number;
}
interface HSMIntegrityResult {
valid: boolean;
details: string;
}
interface HashOperationData {
input: string | Uint8Array;
algorithm: string;
iterations: number;
}
interface AgilityHashOptions {
primaryAlgorithm?: "sha256" | "sha512" | "blake3" | "sha3-256";
fallbackAlgorithms?: string[];
futureProof?: boolean;
outputFormat?: "hex" | "base64" | "buffer";
}
/**
* Hash utilities - Common utility functions for hash operations
*/
declare class HashUtils {
/**
* Format hash output in the specified format
* @param data - Data to format
* @param format - Output format
* @returns Formatted output
*/
static formatOutput(data: Uint8Array | Buffer, format?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer"): string | Buffer;
/**
* Get strength-based configuration
* @param strength - Hash strength level
* @returns Configuration object
*/
static getStrengthConfiguration(strength: HashStrength): StrengthConfiguration;
/**
* Get Argon2 configuration based on strength
* @param strength - Hash strength level
* @returns Argon2 configuration
*/
static getArgon2Configuration(strength: HashStrength): StrengthConfiguration;
/**
* Get scrypt configuration based on strength
* @param strength - Hash strength level
* @returns Scrypt configuration
*/
static getScryptConfiguration(strength: HashStrength): {
N: number;
r: number;
p: number;
};
/**
* Perform secure memory wipe
* @param input - Input to wipe
* @param salt - Salt to wipe
* @param pepper - Pepper to wipe
*/
static performSecureWipe(input: string | Buffer | Uint8Array, salt?: string | Buffer | Uint8Array, pepper?: string | Buffer | Uint8Array): void;
/**
* Validate hash algorithm
* @param algorithm - Algorithm to validate
* @returns True if valid
*/
static isValidAlgorithm(algorithm: string): boolean;
/**
* Get algorithm security level
* @param algorithm - Algorithm to check
* @returns Security level
*/
static getAlgorithmSecurityLevel(algorithm: string): "LOW" | "MEDIUM" | "HIGH" | "MILITARY";
/**
* Convert string or Uint8Array to Buffer
* @param input - Input to convert
* @returns Buffer
*/
static toBuffer(input: string | Uint8Array | Buffer): Buffer;
/**
* Generate random salt with specified length
* @param length - Salt length in bytes
* @returns Random salt buffer
*/
static generateRandomSalt(length: number): Buffer;
/**
* Combine multiple buffers securely
* @param buffers - Buffers to combine
* @returns Combined buffer
*/
static combineBuffers(buffers: Buffer[]): Buffer;
/**
* XOR two buffers of equal length
* @param a - First buffer
* @param b - Second buffer
* @returns XORed result
*/
static xorBuffers(a: Buffer, b: Buffer): Buffer;
}
/**
* Hash validator - Input validation and security checks
*/
declare class HashValidator {
/**
* Validate hash input for security
* @param input - Input to validate
* @param options - Validation options
*/
static validateHashInput(input: string | Uint8Array, options: EnhancedHashOptions): void;
/**
* Check for weak patterns in input
* @param input - String input to check
* @returns True if weak patterns found
*/
private static hasWeakPatterns;
/**
* Validate hash options
* @param options - Options to validate
*/
private static validateOptions;
/**
* Validate password strength
* @param password - Password to validate
* @returns Validation result
*/
static validatePasswordStrength(password: string): {
isSecure: boolean;
score: number;
issues: string[];
recommendations: string[];
};
/**
* Enhanced timing-safe string comparison
* @param a - First string/buffer
* @param b - Second string/buffer
* @returns True if equal
*/
static timingSafeEqual(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
/**
* Manual timing-safe comparison implementation
*/
private static manualTimingSafeEqual;
/**
* Validate salt quality
* @param salt - Salt to validate
* @returns Validation result
*/
static validateSalt(salt: string | Buffer | Uint8Array): {
isValid: boolean;
issues: string[];
recommendations: string[];
};
}
/**
* Hash Algorithms - Enterprise-grade cryptographic hashing
* Maintains backward compatibility while adding quantum-resistant features
*/
declare class HashAlgorithms {
private static readonly QUANTUM_ALGORITHMS;
private static readonly SECURITY_CONSTANTS;
/**
* Initialize crypto libraries asynchronously (NEW METHOD)
*/
static initialize(): Promise<void>;
/**
* Core secure hash function with multiple algorithm support
*
* BEHAVIOR: This method produces consistent hashes for the same input. Unlike Hash.createSecureHash(), this method
* does NOT auto-generate random salts, ensuring deterministic results.
*
* Use this method when you need:
* - Consistent hashes for data integrity verification
* - Content-based hashing (like file checksums)
* - Deterministic hash generation
*
* @param input - Input to hash
* @param options - Hash options (salt is optional and won't be auto-generated)
* @returns Hash result (consistent for same input/options)
*/
static secureHash(input: string | Uint8Array, options?: {
algorithm?: string;
iterations?: number;
salt?: string | Buffer | Uint8Array;
pepper?: string | Buffer | Uint8Array;
outputFormat?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer";
}): string | Buffer;
/**
* more algorithms and better implementations
* Hash data with specified algorithm
* @param data - Data to hash
* @param algorithm - Algorithm to use
* @returns Hash result
*/
private static hashWithAlgorithm;
/**
* real BLAKE3 implementation
* BLAKE3 hash implementation
* @param data - Data to hash
* @returns BLAKE3 hash
*/
private static blake3Hash;
/**
* real BLAKE2b implementation
* BLAKE2b hash implementation
* @param data - Data to hash
* @returns BLAKE2b hash
*/
private static blake2bHash;
/**
* real BLAKE2s implementation
* BLAKE2s hash implementation
* @param data - Data to hash
* @returns BLAKE2s hash
*/
private static blake2sHash;
/**
* better security parameters
* PBKDF2 hash implementation
* @param data - Data to hash
* @returns PBKDF2 hash
*/
private static pbkdf2Hash;
/**
* better constants and rounds
* Fallback BLAKE3 implementation (simplified)
* @param data - Data to hash
* @returns Simplified BLAKE3-like hash
*/
private static fallbackBlake3;
/**
* quantum resistance option
* Enhanced HMAC generation
* @param algorithm - Hash algorithm
* @param key - HMAC key
* @param data - Data to authenticate
* @param options - HMAC options
* @returns HMAC digest
*/
static createSecureHMAC(algorithm: "sha256" | "sha512" | "sha3-256" | "sha3-512", key: string | Buffer | Uint8Array, data: string | Buffer | Uint8Array, options?: {
encoding?: "hex" | "base64" | "base64url";
keyDerivation?: boolean;
iterations?: number;
}): string;
/**
* better algorithm selection and quantum resistance
* Multi-algorithm hash for quantum resistance
* @param input - Input to hash
* @param algorithms - Algorithms to use
* @param iterations - Iterations per algorithm
* @returns Combined hash result
*/
static multiAlgorithmHash(input: string | Uint8Array, algorithms?: string[], iterations?: number): Buffer;
/**
* better chunk processing and algorithms
* Streamed hash for large data
* @param algorithm - Hash algorithm
* @param chunkSize - Chunk size for processing
* @returns Hash stream processor
*/
static createStreamHash(algorithm?: string, chunkSize?: number): {
update: (chunk: Buffer) => void;
digest: () => Buffer;
reset: () => void;
};
/**
* better timing attack prevention
* Constant-time hash comparison
* @param hash1 - First hash
* @param hash2 - Second hash
* @returns True if hashes match
*/
static constantTimeCompare(hash1: string | Buffer, hash2: string | Buffer): boolean;
/**
* NEW METHOD - Ultra-secure hash function with quantum resistance
*/
static quantumResistantHash(input: string | Uint8Array, options?: SecureHashOptions): Promise<string | Buffer>;
/**
* NEW METHOD - Argon2 key derivation
*/
private static argon2Derive;
/**
* NEW METHOD - Scrypt key derivation
*/
private static scryptDerive;
/**
* NEW METHOD - BCrypt key derivation
*/
private static bcryptDerive;
/**
* NEW METHOD - Enhanced PBKDF2 key derivation
*/
private static pbkdf2Derive;
/**
* NEW METHOD - Multi-algorithm quantum-resistant hashing
*/
private static multiQuantumHash;
/**
* NEW METHOD - Ultra-secure HMAC with quantum resistance
*/
static createQuantumHMAC(algorithm: string, key: string | Buffer | Uint8Array, data: string | Buffer | Uint8Array, options?: {
encoding?: "hex" | "base64" | "base64url";
keyDerivation?: boolean;
iterations?: number;
quantumResistant?: boolean;
}): Promise<string>;
/**
* NEW METHOD - BLAKE3-based HMAC
*/
private static blake3HMAC;
/**
* NEW METHOD - Secure random salt generation
*/
static generateSecureSalt(size?: number): Buffer;
/**
* NEW METHOD - Enhanced secure comparison with additional timing normalization
*/
static secureCompare(hash1: string | Buffer, hash2: string | Buffer): boolean;
/**
* NEW METHOD - Secure hash verification
*/
static verifyHash(input: string | Uint8Array, expectedHash: string | Buffer, options?: SecureHashOptions): Promise<boolean>;
/**
* NEW METHOD - Memory-hard proof of work
*/
static proofOfWork(challenge: string, difficulty?: number): Promise<{
nonce: string;
hash: string;
attempts: number;
}>;
}
/**
* Hash security features - security implementations
*/
declare class HashSecurity {
private static readonly DEFAULT_PBKDF2_ITERATIONS;
private static readonly DEFAULT_MEMORY_COST;
private static readonly QUANTUM_SALT_SIZE;
private static readonly HSM_KEY_SIZE;
/**
* Hardware Security Module (HSM) compatible hashing
* Production implementation using standard cryptographic practices
*/
static hsmCompatibleHash(input: string | Uint8Array, options?: HSMHashOptions): string | Buffer;
/**
* Derive HSM-compatible key using production-grade key derivation
*/
private static deriveHSMKey;
/**
* Verify HSM integrity using cryptographic verification
*/
private static verifyHSMIntegrity;
/**
* Validate hash format and content
*/
private static isValidHashFormat;
/**
* Enhanced security monitoring with real threat detection
*/
static monitorHashSecurity(operation: string, data: HashOperationData): HashMonitoringResult;
/**
* Optimized timing-safe hashing with constant-time operations
*/
static timingSafeHash(input: string | Uint8Array, options?: {
algorithm?: string;
iterations?: number;
salt?: string | Buffer | Uint8Array;
outputFormat?: "hex" | "base64" | "buffer";
targetTime?: number;
}): string | Buffer;
/**
* Memory-hard hashing using Argon2
*/
static memoryHardHash(input: string | Uint8Array, options?: {
memoryCost?: number;
timeCost?: number;
parallelism?: number;
hashLength?: number;
salt?: string | Buffer | Uint8Array;
outputFormat?: "hex" | "base64" | "buffer";
}): Promise<string | Buffer>;
/**
* Quantum-resistant hashing with multiple algorithms
*/
static quantumResistantHash(input: string | Uint8Array, options?: {
algorithms?: string[];
iterations?: number;
salt?: string | Buffer | Uint8Array;
outputFormat?: "hex" | "base64" | "buffer";
}): string | Buffer;
/**
* Map algorithm names to Node.js crypto algorithms
*/
private static mapToNodeAlgorithm;
/**
* Enhanced secure verification with multiple protection layers
*/
static secureVerify(input: string | Uint8Array, expectedHash: string | Buffer, options?: {
algorithm?: string;
iterations?: number;
salt?: string | Buffer | Uint8Array;
constantTime?: boolean;
}): boolean;
/**
* Optimized manual constant-time comparison with early termination protection
*/
private static manualConstantTimeCompare;
/**
* Utility method for secure random salt generation with quantum resistance
*/
static generateQuantumSafeSalt(length?: number): Buffer;
/**
* Batch hash verification for improved performance
*/
static batchVerify(inputs: Array<{
input: string | Uint8Array;
expectedHash: string | Buffer;
}>, options?: {
algorithm?: string;
iterations?: number;
salt?: string | Buffer | Uint8Array;
constantTime?: boolean;
}): boolean[];
}
/**
* Hash advanced features - Optimized hash implementations
*/
declare class HashAdvanced {
private static readonly CHUNK_SIZE;
private static readonly MAX_WORKERS;
/**
* Cryptographic agility - support for algorithm migration
* @param input - Input to hash
* @param options - Migration options
* @returns Hash with algorithm metadata
*/
static agilityHash(input: string | Uint8Array, options?: AgilityHashOptions): HashAgilityResult;
/**
* Side-channel attack resistant hashing
* @param input - Input to hash
* @param options - Resistance options
* @returns Side-channel resistant hash
*/
static sideChannelResistantHash(input: string | Uint8Array, options?: SideChannelOptions): string | Buffer;
/**
* Constant-time hash processing
* @param inputBuffer - Input buffer
* @param memoryProtection - Enable memory protection
* @param outputFormat - Output format
* @returns Constant-time hash
*/
private static constantTimeHash;
/**
* Power analysis resistant hash processing - optimized implementation
* @param inputBuffer - Input buffer
* @param outputFormat - Output format
* @returns Power analysis resistant hash
*/
private static powerAnalysisResistantHash;
/**
* tse.ExecutionResultparallel hash processing using worker threads
* @param input - Input to hash
* @param options - Parallel processing options
* @returns Promise resolving to hash result
*/
static parallelHash(input: string | Uint8Array, options?: {
chunkSize?: number;
workers?: number;
algorithm?: string;
outputFormat?: "hex" | "base64" | "buffer";
}): Promise<string | Buffer>;
/**
* Optimized streaming hash for large data processing
* @param algorithm - Hash algorithm
* @param options - Streaming options
* @returns Stream hash processor
*/
static createStreamingHash(algorithm?: string, options?: {
chunkSize?: number;
progressCallback?: (processed: number, total?: number) => void;
}): {
update: (chunk: Buffer) => void;
digest: () => Buffer;
reset: () => void;
getProgress: () => {
processed: number;
chunks: number;
};
};
/**
* Optimized Merkle tree hash for data integrity
* @param data - Array of data chunks
* @param algorithm - Hash algorithm
* @returns Merkle root hash
*/
static merkleTreeHash(data: (string | Uint8Array | Buffer)[], algorithm?: string): Buffer;
/**
* Optimized incremental hash for append-only data
* @param previousHash - Previous hash state
* @param newData - New data to append
* @param algorithm - Hash algorithm
* @returns Updated hash
*/
static incrementalHash(previousHash: string | Buffer, newData: string | Uint8Array | Buffer, algorithm?: string): Buffer;
/**
* Optimized hash chain for sequential data integrity
* @param data - Array of data items
* @param algorithm - Hash algorithm
* @returns Array of chained hashes
*/
static hashChain(data: (string | Uint8Array | Buffer)[], algorithm?: string): Buffer[];
/**
* Batch hash processing for multiple inputs
* @param inputs - Array of inputs to hash
* @param algorithm - Hash algorithm
* @param outputFormat - Output format
* @returns Array of hashes
*/
static batchHash(inputs: (string | Uint8Array | Buffer)[], algorithm?: string, outputFormat?: "hex" | "base64" | "buffer"): (string | Buffer)[];
/**
* Memory-efficient hash verification
* @param input - Input to verify
* @param expectedHash - Expected hash value
* @param algorithm - Hash algorithm
* @returns True if hash matches
*/
static verifyHash(input: string | Uint8Array | Buffer, expectedHash: string | Buffer, algorithm?: string): boolean;
}
/**
* Hash entropy analysis and quality assessment
*/
declare class HashEntropy {
/**
* Advanced entropy analysis for hash quality assessment
* @param data - Data to analyze
* @returns Entropy analysis results
*/
static analyzeHashEntropy(data: Buffer | Uint8Array): HashEntropyAnalysis;
/**
* Perform statistical randomness tests
* @param data - Data to test
* @returns Test results
*/
static performRandomnessTests(data: Buffer): {
monobitTest: {
passed: boolean;
score: number;
};
runsTest: {
passed: boolean;
score: number;
};
frequencyTest: {
passed: boolean;
score: number;
};
serialTest: {
passed: boolean;
score: number;
};
overallScore: number;
};
/**
* Monobit test - checks balance of 0s and 1s
* @param data - Data to test
* @returns Test result
*/
private static monobitTest;
/**
* Runs test - checks for proper distribution of runs
* @param data - Data to test
* @returns Test result
*/
private static runsTest;
/**
* Frequency test - checks distribution of byte values
* @param data - Data to test
* @returns Test result
*/
private static frequencyTest;
/**
* Serial test - checks correlation between consecutive bytes
* @param data - Data to test
* @returns Test result
*/
private static serialTest;
/**
* Estimate entropy rate of data
* @param data - Data to analyze
* @returns Entropy rate in bits per byte
*/
static estimateEntropyRate(data: Buffer): number;
/**
* Generate entropy quality report
* @param data - Data to analyze
* @returns Comprehensive entropy report
*/
static generateEntropyReport(data: Buffer): {
analysis: HashEntropyAnalysis;
randomnessTests: ReturnType<typeof HashEntropy.performRandomnessTests>;
entropyRate: number;
recommendations: string[];
overallGrade: "POOR" | "FAIR" | "GOOD" | "EXCELLENT";
};
}
/**
* Hash Core - Main Hash class with modular architecture
* This is the primary interface for all hashing operations
*/
/**
* Military-grade hashing functionality with enhanced security features
* Modular architecture for maintainable and scalable hash operations
*/
declare class Hash {
/**
* Create secure hash with military-grade security options
*
* IMPORTANT: This method automatically generates a random salt
* when no salt is provided, resulting in different hashes for the same input.
* This is designed for password hashing where randomness enhances security.
*
* For consistent hashes, either:
* - Provide a fixed salt parameter, or
* - Use Hash.create() method instead
*
* @param input - The input to hash
* @param salt - Salt for the hash (if not provided, random salt is auto-generated)
* @param options - Enhanced hashing options
* @returns The hash in the specified format
*/
static createSecureHash(input: string | Uint8Array, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): string | Promise<string>;
/**
* Verify hash with secure comparison
* @param input - Input to verify
* @param expectedHash - Expected hash value
* @param salt - Salt used in original hash
* @param options - Verification options
* @returns True if hash matches
*/
static verifyHash(input: string | Uint8Array, expectedHash: string | Buffer, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): boolean;
/**
* Async verify hash with secure comparison
* @param input - Input to verify
* @param expectedHash - Expected hash value
* @param salt - Salt used in original hash
* @param options - Verification options
* @returns Promise resolving to true if hash matches
*/
static verifyHashAsync(input: string | Uint8Array, expectedHash: string | Buffer, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): Promise<boolean>;
/**
* Enhanced PBKDF2 key derivation
*/
static deriveKeyPBKDF2: typeof HashSecurity.memoryHardHash;
/**
* Enhanced scrypt key derivation
*/
static deriveKeyScrypt(password: string | Buffer, salt: string | Buffer, keyLength?: number, options?: {
N?: number;
r?: number;
p?: number;
encoding?: "hex" | "base64" | "buffer";
validateStrength?: boolean;
}): string | Buffer;
/**
* Enhanced Argon2 key derivation
*/
static deriveKeyArgon2: typeof HashSecurity.memoryHardHash;
/**
* Standard PBKDF2 key derivation
*
* BEHAVIOR: Uses Node.js crypto.pbkdf2Sync for reliable, standard PBKDF2 implementation.
* Produces consistent results and is widely compatible.
* With crypto:
* @example
* crypto.pbkdf2Sync(
password,
salt,
iterations,
keyLength,
hashFunction
);
*
* @param password - Password to derive key from
* @param salt - Salt for the derivation
* @param iterations - Number of iterations (default: 100000)
* @param keyLength - Desired key length in bytes (default: 32)
* @param hashFunction - Hash function to use (default: "sha256")
* @param outputFormat - Output format (default: "hex")
* @returns PBKDF2 derived key
*/
static pbkdf2(password: string, salt: string, iterations?: number, keyLength?: number, hashFunction?: "sha256" | "sha512", outputFormat?: "hex" | "base64" | "buffer"): string | Buffer;
/**
* Hardware Security Module (HSM) compatible hashing
*/
static hsmCompatibleHash: typeof HashSecurity.hsmCompatibleHash;
/**
* Cryptographic agility hash
*/
static agilityHash: typeof HashAdvanced.agilityHash;
/**
* Side-channel attack resistant hashing
*/
static sideChannelResistantHash: typeof HashAdvanced.sideChannelResistantHash;
/**
* Real-time security monitoring
*/
static monitorHashSecurity: typeof HashSecurity.monitorHashSecurity;
/**
* Analyze hash entropy
*/
static analyzeHashEntropy: typeof HashEntropy.analyzeHashEntropy;
/**
* Generate entropy report
*/
static generateEntropyReport: typeof HashEntropy.generateEntropyReport;
/**
* Perform randomness tests
*/
static performRandomnessTests: typeof HashEntropy.performRandomnessTests;
/**
* Validate password strength
*/
static validatePasswordStrength: typeof HashValidator.validatePasswordStrength;
/**
* Timing-safe string comparison
*/
static timingSafeEqual: typeof HashValidator.timingSafeEqual;
/**
* Validate salt quality
*/
static validateSalt: typeof HashValidator.validateSalt;
/**
* Parallel hash processing
*/
static parallelHash: typeof HashAdvanced.parallelHash;
/**
* Streaming hash for large data
*/
static createStreamingHash: typeof HashAdvanced.createStreamingHash;
/**
* Merkle tree hash
*/
static merkleTreeHash: typeof HashAdvanced.merkleTreeHash;
/**
* Incremental hash
*/
static incrementalHash: typeof HashAdvanced.incrementalHash;
/**
* Hash chain
*/
static hashChain: typeof HashAdvanced.hashChain;
/**
* Format hash output
*/
static formatOutput: typeof HashUtils.formatOutput;
/**
* Get strength configuration
*/
static getStrengthConfiguration: typeof HashUtils.getStrengthConfiguration;
/**
* Get algorithm security level
*/
static getAlgorithmSecurityLevel: typeof HashUtils.getAlgorithmSecurityLevel;
/**
* Handle secure wipe if requested
* IMPORTANT: Only wipe copies, not the original salt/pepper that might be needed for verification
*/
private static handleSecureWipe;
/**
* Legacy secure hash method (for backward compatibility)
*
* BEHAVIOR: Produces consistent hashes for the same input (like CryptoJS).
* This method does NOT auto-generate random salts, ensuring deterministic results.
*
* For password hashing with auto-salt generation, use Hash.createSecureHash() instead.
*/
static create: typeof HashAlgorithms.secureHash;
/**
* Legacy HMAC creation (for backward compatibility)
*/
static createSecureHMAC: typeof HashAlgorithms.createSecureHMAC;
}
/**
* Random types - Type definitions and interfaces for random operations
*/
type EncodingHashType = "hex" | "base64" | "base58" | "buffer";
declare enum RNGState {
UNINITIALIZED = "uninitialized",
INITIALIZING = "initializing",
READY = "ready",
ERROR = "error",
RESEEDING = "reseeding"
}
declare enum EntropyQuality {
POOR = "poor",
FAIR = "fair",
GOOD = "good",
EXCELLENT = "excellent",
MILITARY = "military"
}
interface SodiumInterface {
ready: Promise<void> | boolean;
randombytes_buf: (size: number) => Uint8Array;
crypto_secretbox_NONCEBYTES: number;
crypto_secretbox_KEYBYTES: number;
crypto_aead_chacha20poly1305_ietf_encrypt: (message: Uint8Array, additionalData: Uint8Array | null, secretNonce: Uint8Array | null, publicNonce: Uint8Array, key: Uint8Array) => Uint8Array;
crypto_aead_chacha20poly1305_ietf_decrypt: (secretNonce: Uint8Array | null, ciphertext: Uint8Array, additionalData: Uint8Array | null, publicNonce: Uint8Array, key: Uint8Array) => Uint8Array;
}
interface ForgeInterface {
random: {
getBytesSync: (count: number) => string;
};
}
interface SecureRandomInterface {
randomBytes?: (size: number) => Uint8Array;
(size: number): Uint8Array;
}
interface RandomBytesInterface {
(size: number): Buffer;
}
interface TweetNaClInterface {
randomBytes: (size: number) => Uint8Array;
}
interface NobleHashesInterface {
sha256: (data: Uint8Array) => Uint8Array;
sha512: (data: Uint8Array) => Uint8Array;
blake3?: (data: Uint8Array) => Uint8Array;
}
interface RandomGenerationOptions {
useEntropyPool?: boolean;
quantumSafe?: boolean;
reseedThreshold?: number;
securityLevel?: SecurityLevel$1;
validateOutput?: boolean;
}
interface EntropySourceConfig {
name: string;
enabled: boolean;
priority: number;
fallbackAvailable: boolean;
lastUsed?: number;
errorCount?: number;
}
interface QuantumSafeOptions$1 {
enabled: boolean;
algorithm?: "kyber" | "dilithium" | "falcon";
keySize?: number;
additionalEntropy?: boolean;
}
interface TokenGenerationOptions {
includeUppercase?: boolean;
includeLowercase?: boolean;
includeNumbers?: boolean;
includeSymbols?: boolean;
excludeSimilarCharacters?: boolean;
entropyLevel?: SecurityLevel$1;
outputFormat?: EncodingHashType;
customCharset?: string;
minEntropy?: number;
}
interface IVGenerationOptions {
algorithm?: "aes-128-cbc" | "aes-192-cbc" | "aes-256-cbc" | "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm" | "aes-128-ctr" | "aes-192-ctr" | "aes-256-ctr" | "chacha20" | "chacha20-poly1305" | "des-ede3-cbc" | "blowfish-cbc";
quantumSafe?: boolean;
useEntropyPool?: boolean;
validateSize?: boolean;
}
interface CryptoUtilityOptions {
keySize?: number;
algorithm?: string;
quantumSafe?: boolean;
useHardwareEntropy?: boolean;
validateStrength?: boolean;
}
interface SecurityMonitoringResult {
entropyQuality: EntropyQuality;
securityLevel: SecurityLevel$1;
threats: string[];
recommendations: string[];
timestamp: number;
bytesGenerated: number;
reseedCount: number;
libraryStatus: Record<string, boolean>;
}
interface EntropyAnalysisResult$1 {
shannonEntropy: number;
minEntropy: number;
compressionRatio: number;
randomnessScore: number;
qualityGrade: EntropyQuality;
recommendations: string[];
testResults: {
monobitTest: {
passed: boolean;
score: number;
};
runsTest: {
passed: boolean;
score: number;
};
frequencyTest: {
passed: boolean;
score: number;
};
serialTest: {
passed: boolean;
score: number;
};
};
}
interface LibraryStatus extends Record<string, boolean> {
sodium: boolean;
forge: boolean;
secureRandom: boolean;
randombytes: boolean;
nobleHashes: boolean;
tweetnacl: boolean;
kyber: boolean;
entropyString: boolean;
cryptoJs: boolean;
elliptic: boolean;
nobleCurves: boolean;
}
interface RandomState {
entropyPool: Buffer;
lastReseed: number;
state: RNGState;
bytesGenerated: number;
entropyQuality: EntropyQuality;
securityLevel: SecurityLevel$1;
quantumSafeMode: boolean;
reseedCounter: number;
hardwareEntropyAvailable: boolean;
sidechannelProtection: boolean;
entropyAugmentation: boolean;
realTimeMonitoring: boolean;
lastEntropyTest: number;
entropyTestResults: Map<string, number>;
securityAlerts: string[];
additionalEntropySources: Map<string, () => Buffer>;
}
type EntropySourceFunction = () => Buffer;
type SecurityValidator = (data: Uint8Array) => boolean;
type EntropyCollector = (size: number) => Buffer;
interface AlgorithmConfig {
name: string;
keySize: number;
ivSize: number;
blockSize: number;
securityLevel: SecurityLevel$1;
quantumResistant: boolean;
}
interface CipherConfig extends AlgorithmConfig {
mode: "cbc" | "gcm" | "ctr" | "ecb";
authTagLength?: number;
nonceSize?: number;
}
type RandomOptions = RandomGenerationOptions & QuantumSafeOptions$1 & CryptoUtilityOptions;
type AllRandomTypes = RandomState & SecurityMonitoringResult & EntropyAnalysisResult$1;
type EncodingType = "hex" | "base64" | "base64url" | "base58" | "binary" | "utf8" | BaseEncodingType;
/**
* Enhanced Uint8Array with encoding support and improved security
*/
declare class EnhancedUint8Array extends Uint8Array {
private _isCleared;
/**
* Convert to string with specified encoding
* @param encoding - Encoding type (optional, defaults to hex for security)
* @returns Encoded string
*/
toString(encoding?: EncodingType): string;
/**
* Secure hex conversion
*/
private _toHexSecure;
/**
* Secure base64 conversion
*/
private _toBase64Secure;
/**
* Secure Base58 conversion with improved error handling
*/
private _toBase58Secure;
/**
* Secure binary conversion
*/
private _toBinarySecure;
/**
* Secure UTF-8 conversion
*/
private _toUtf8Secure;
/**
* Get entropy information with enhanced analysis
*/
getEntropyInfo(): {
bytes: number;
bits: number;
quality: string;
entropy: number;
};
/**
* Calculate Shannon entropy for quality assessment
*/
private _calculateShannonEntropy;
/**
* Get quality rating based on entropy and length
*/
private _getQualityRating;
/**
* Get as Buffer with proper typing and security
* @returns Buffer<ArrayBufferLike> containing the same data
*/
getBuffer(): Buffer<ArrayBufferLike>;
/**
* Securely clear the array contents
*/
clear(): void;
/**
* Check if array has been cleared
*/
private _checkCleared;
/**
* Create a secure copy of the array
*/
secureClone(): EnhancedUint8Array;
/**
* Compare with another array in constant time to prevent timing attacks
*/
constantTimeEquals(other: Uint8Array): boolean;
/**
* Convert to regular Uint8Array for safe Buffer operations
*/
toUint8Array(): Uint8Array;
/**
* Override valueOf to provide safe primitive conversion
* Returns this instance for Buffer.from() compatibility
*/
valueOf(): this;
}
/**
* ## Core Cryptographic Exports
*
* Primary cryptographic classes and utilities for secure random generation,
* key management, validation, and buffer operations.
*/
/**
* ### Secure Random Generation
*
* High-entropy random number and data generation with multiple entropy sources.
* Provides cryptographically secure random values for all security operations.
*
* @example
* ```typescript
* import { Random } from "xypriss-security";
*
* // Generate secure random bytes
* const randomBytes = Random.getRandomBytes(32);
*
* // Generate secure UUID
* const uuid = Random.generateSecureUUID();
*
* // Generate random integers
* const randomInt = Random.getSecureRandomInt(1, 100);
* ```
*/
declare class SecureRandom {
private static instance;
private state;
private stats;
private constructor();
/**
* Get singleton instance
*/
static getInstance(): SecureRandom;
/**
* Initialize entropy pool
*/
private initializeEntropyPool;
/**
* Setup additional entropy sources
*/
private setupAdditionalEntropySources;
/**
* Detect hardware entropy availability
*/
private detectHardwareEntropy;
/**
* Generate ultra-secure random bytes with enhanced entropy
* @param length - Number of bytes to generate
* @param options - Generation options
* @returns Enhanced random bytes
*/
static getRandomBytes(length: number, options?: RandomGenerationOptions): EnhancedUint8Array;
/**
* Get system random bytes (fallback method)
*/
static getSystemRandomBytes(length: number): Uint8Array;
/**
* Generate secure random integer
*/
static getSecureRandomInt(min: number, max: number, options?: RandomGenerationOptions): number;
/**
* Generate secure UUID v4
*/
static generateSecureUUID(options?: RandomGenerationOptions): string;
/**
* Generate secure random float
*/
static getSecureRandomFloat(options?: RandomGenerationOptions): number;
/**
* Generate secure random boolean
*/
static getSecureRandomBoolean(options?: RandomGenerationOptions): boolean;
/**
* Generate salt
*/
static generateSalt(length?: number, options?: RandomGenerationOptions): Buffer;
/**
* Reseed entropy pool
*/
reseedEntropyPool(): void;
/**
* Get entropy analysis
*/
static getEntropyAnalysis(data?: Buffer): EntropyAnalysisResult$1;
/**
* Assess entropy quality
*/
static assessEntropyQuality(data: Buffer): EntropyQuality;
/**
* Get security monitoring result
*/
static getSecurityStatus(): SecurityMonitoringResult;
/**
* Get library status
*/
static getLibraryStatus(): LibraryStatus;
/**
* Check if secure random is available
*/
static isSecureRandomAvailable(): boolean;
/**
* Get current state
*/
getState(): RandomState;
/**
* Get statistics
*/
static getStatistics(): {
bytesGenerated: number;
reseedCount: number;
lastReseed: number;
entropyQuality: EntropyQuality;
state: RNGState;
};
/**
* Reset instance (for testing)
*/
static resetInstance(): void;
/**
* Enable quantum-safe mode
*/
static enableQuantumSafeMode(): void;
/**
* Disable quantum-safe mode
*/
static disableQuantumSafeMode(): void;
/**
* Set security level
*/
static setSecurityLevel(level: SecurityLevel$1): void;
}
/**
* Random entropy - Entropy pool management and quality assessment
*/
declare class RandomEntropy {
/**
* Initialize entropy pool with multiple sources
*/
static initializeEntropyPool(poolSize?: number): Promise<Buffer>;
/**
* Gather secondary entropy from various sources
*/
static gatherSecondaryEntropy(): Promise<Buffer>;
/**
*