UNPKG

@iota-big3/sdk-security

Version:

Advanced security features including zero trust, quantum-safe crypto, and ML threat detection

328 lines (327 loc) 11.5 kB
"use strict"; /** * Post-Quantum Cryptography Implementation * NIST-approved quantum-resistant algorithms */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.KeyMigration = exports.QuantumRandomGenerator = exports.HybridCrypto = exports.DilithiumAlgorithm = exports.KyberAlgorithm = exports.PostQuantumAlgorithm = void 0; const crypto = __importStar(require("crypto")); const util_1 = require("util"); const randomBytes = (0, util_1.promisify)(crypto.randomBytes); /** * Abstract base class for post-quantum algorithms */ class PostQuantumAlgorithm { constructor(config) { this.config = config; } } exports.PostQuantumAlgorithm = PostQuantumAlgorithm; /** * CRYSTALS-Kyber implementation (Key Encapsulation) * NIST selected for encryption */ class KyberAlgorithm extends PostQuantumAlgorithm { constructor() { super(...arguments); this.keyLengths = { 1: { pk: 800, sk: 1632, ct: 768, ss: 32 }, // Kyber512, 3: { pk: 1184, sk: 2400, ct: 1088, ss: 32 }, // Kyber768, 5: { pk: 1568, sk: 3168, ct: 1568, ss: 32 } // Kyber1024 }; } async generateKeyPair() { const lengths = this.keyLengths[this?.config?.securityLevel]; // In production, use actual Kyber implementation // For demo, using random bytes const publicKey = await randomBytes(lengths.pk); const privateKey = await randomBytes(lengths.sk); const expiresAt = this?.config?.keyRotationInterval ? new Date(Date.now() + this?.config?.keyRotationInterval * 3600000) : undefined; return { publicKey, privateKey, algorithm: `kyber-${this?.config?.securityLevel}`, securityLevel: this?.config?.securityLevel, createdAt: new Date(), expiresAt }; } async encrypt(publicKey, plaintext) { const lengths = this.keyLengths[this?.config?.securityLevel]; // Kyber is a KEM (Key Encapsulation Mechanism) // 1. Generate shared secret using public key const encapsulatedKey = await randomBytes(lengths.ct); const sharedSecret = await randomBytes(lengths.ss); // 2. Use shared secret with AES-GCM for actual encryption const cipher = crypto.createCipheriv('aes-256-gcm', sharedSecret, await randomBytes(16)); const encrypted = Buffer.concat([ cipher.update(plaintext), cipher.final() ]); return { ciphertext: encrypted, encapsulatedKey, algorithm: `kyber-${this?.config?.securityLevel}`, nonce: cipher.getAuthTag() }; } async decrypt(privateKey, encryptedData) { // 1. Decapsulate to get shared secret const sharedSecret = await this.decapsulate(privateKey, encryptedData.encapsulatedKey); // 2. Decrypt using AES-GCM const decipher = crypto.createDecipheriv('aes-256-gcm', sharedSecret, await randomBytes(16)); if (this.isEnabled) { decipher.setAuthTag(encryptedData.nonce); } return Buffer.concat([ decipher.update(encryptedData.ciphertext), decipher.final() ]); } async sign(privateKey, message) { throw new Error('Kyber does not support signatures. Use Dilithium or Falcon.'); } async verify(publicKey, message, signature) { throw new Error('Kyber does not support signatures. Use Dilithium or Falcon.'); } async decapsulate(privateKey, ciphertext) { // In production, use actual Kyber decapsulation return randomBytes(32); } } exports.KyberAlgorithm = KyberAlgorithm; /** * CRYSTALS-Dilithium implementation (Digital Signatures) * NIST selected for signatures */ class DilithiumAlgorithm extends PostQuantumAlgorithm { constructor() { super(...arguments); this.parameters = { 1: { pk: 1312, sk: 2528, sig: 2420 }, // Dilithium2, 3: { pk: 1952, sk: 4000, sig: 3293 }, // Dilithium3, 5: { pk: 2592, sk: 4864, sig: 4595 } // Dilithium5 }; } async generateKeyPair() { const params = this.parameters[this?.config?.securityLevel]; return { publicKey: await randomBytes(params.pk), privateKey: await randomBytes(params.sk), algorithm: `dilithium-${this?.config?.securityLevel}`, securityLevel: this?.config?.securityLevel, createdAt: new Date() }; } async encrypt(publicKey, plaintext) { throw new Error('Dilithium does not support encryption. Use Kyber.'); } async decrypt(privateKey, encryptedData) { throw new Error('Dilithium does not support encryption. Use Kyber.'); } async sign(privateKey, message) { const params = this.parameters[this?.config?.securityLevel]; // In production, use actual Dilithium signing const signature = await randomBytes(params.sig); return { signature, algorithm: `dilithium-${this?.config?.securityLevel}`, publicKey: Buffer.alloc(0) // Would extract from private key }; } async verify(publicKey, message, signature) { // In production, use actual Dilithium verification return true; } } exports.DilithiumAlgorithm = DilithiumAlgorithm; /** * Hybrid Cryptography - Combines classical and post-quantum */ class HybridCrypto { constructor(config, classicalAlgorithm = 'ecdsa') { this.config = config; this.classical = new ClassicalCrypto(classicalAlgorithm); switch (config.algorithm) { case 'kyber': this.postQuantum = new KyberAlgorithm(config); break; case 'dilithium': this.postQuantum = new DilithiumAlgorithm(config); break; default: throw new Error(`Unsupported algorithm: ${config.algorithm}`); } } } exports.HybridCrypto = HybridCrypto; > { const: [classical, postQuantum] = await Promise.all([ this?.classical?.generateKeyPair(), this?.postQuantum?.generateKeyPair() ]), return: { classical, postQuantum } }; /** * Hybrid encryption - uses both algorithms */ async; encrypt(classicalPublicKey, crypto.KeyObject, quantumPublicKey, Buffer, plaintext, Buffer); Promise < { classical: Buffer, quantum: EncryptedData } > { // Generate random key for classical encryption const: symmetricKey = await randomBytes(32), // Encrypt symmetric key with both algorithms const: classicalEncrypted = crypto.publicEncrypt(classicalPublicKey, symmetricKey), const: quantumEncrypted = await this?.postQuantum?.encrypt(quantumPublicKey, symmetricKey), // Encrypt actual data with symmetric key const: cipher = crypto.createCipheriv('aes-256-gcm', symmetricKey, await randomBytes(16)), const: encrypted = Buffer.concat([ cipher.update(plaintext), cipher.final() ]), return: { classical: classicalEncrypted, quantum: { ...quantumEncrypted, ciphertext: encrypted } } }; /** * Hybrid signatures - signs with both algorithms */ async; sign(classicalPrivateKey, crypto.KeyObject, quantumPrivateKey, Buffer, message, Buffer); Promise < { classical: Buffer, quantum: Signature } > { const: classicalSig = crypto.sign('sha256', message, classicalPrivateKey), const: quantumSig = await this?.postQuantum?.sign(quantumPrivateKey, message), return: { classical: classicalSig, quantum: quantumSig } }; /** * Classical cryptography wrapper */ class ClassicalCrypto { constructor(algorithm) { this.algorithm = algorithm; } async generateKeyPair() { return crypto.generateKeyPairSync(this.algorithm === 'rsa' ? 'rsa' : 'ec', this.algorithm === 'rsa'); { modulusLength: 3072; } { namedCurve: 'P-384'; } } } /** * Quantum Random Number Generator */ class QuantumRandomGenerator { constructor() { this.entropy = Buffer.alloc(0); } /** * Get quantum random bytes * In production, would interface with QRNG hardware */ async getRandomBytes(length) { // Mix system entropy with "quantum" entropy const systemEntropy = await randomBytes(length); const quantumEntropy = await this.getQuantumEntropy(length); // XOR mixing for additional security const mixed = Buffer.alloc(length); for (let i = 0; i < length; i++) { mixed[i] = systemEntropy[i] ^ quantumEntropy[i]; } return mixed; } async getQuantumEntropy(length) { // In production, interface with QRNG hardware // For demo, using crypto random return randomBytes(length); } } exports.QuantumRandomGenerator = QuantumRandomGenerator; /** * Key migration utilities */ class KeyMigration { } exports.KeyMigration = KeyMigration; > { const: pqAlgo = algorithm.algorithm === 'kyber' ? new KyberAlgorithm(algorithm) : , new: DilithiumAlgorithm(algorithm), const: started = new Date(), const: postQuantum = await pqAlgo.generateKeyPair(), const: completed = new Date(), return: { postQuantum, migration: { started, completed, algorithm: algorithm.algorithm } } }; createMigrationReport(totalKeys, number, migratedKeys, number, algorithm, string); MigrationReport; { return { totalKeys, migratedKeys, percentComplete: (migratedKeys / totalKeys) * 100, algorithm, estimatedCompletionTime: new Date(Date.now() + (totalKeys - migratedKeys) * 1000 // 1 sec per key estimate ), recommendations: [ 'Implement key rotation policy', 'Test quantum-safe algorithms in staging', 'Monitor performance impact', 'Plan for increased key sizes' ] }; }