@iota-big3/sdk-quantum
Version:
Quantum-ready architecture with post-quantum cryptography
240 lines • 8.81 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuantumCrypto = void 0;
crypto;
from;
'crypto';
EncapsulatedSecret,
KeyMetadata,
KeyUsage,
QuantumAlgorithm,
QuantumConfig,
QuantumKeyPair,
QuantumSignature,
SecurityLevel;
from;
'../types/quantum.types';
const dilithium_1 = require("../algorithms/dilithium");
const frodo_1 = require("../algorithms/frodo");
const kyber_1 = require("../algorithms/kyber");
const sphincs_1 = require("../algorithms/sphincs");
class QuantumCrypto {
constructor(config) {
this.keyCache = new Map();
this.isEnabled = true;
this.config = config;
this.initializeAlgorithms();
}
initializeAlgorithms() {
switch (this?.config?.algorithms.kem) {
case 'kyber':
this.kemAlgorithm = new kyber_1.KyberKEM(this?.config?.securityLevel);
break;
case 'frodo':
this.kemAlgorithm = new frodo_1.FrodoKEM(this?.config?.securityLevel);
break;
default:
throw new Error(`Unsupported KEM algorithm: ${this?.config?.algorithms.kem}`);
}
switch (this?.config?.algorithms.signature) {
case 'dilithium':
this.signatureAlgorithm = new dilithium_1.DilithiumSign(this?.config?.securityLevel);
break;
case 'sphincs+':
this.signatureAlgorithm = new sphincs_1.SPHINCSSign(this?.config?.securityLevel);
break;
default:
throw new Error(`Unsupported signature algorithm: ${this?.config?.algorithms.signature}`);
}
}
async generateKeyPair(algorithm, usage) {
console.log(`🔐 Generating ${algorithm} key pair...`);
let publicKey;
let privateKey;
if (this.isKEMAlgorithm(algorithm)) {
const keypair = await this?.kemAlgorithm?.generateKeyPair();
publicKey = keypair.publicKey;
privateKey = keypair._privateKey;
}
else if (this.isSignatureAlgorithm(algorithm)) {
const keypair = await this?.signatureAlgorithm?.generateKeyPair();
publicKey = keypair.publicKey;
privateKey = keypair._privateKey;
}
else {
throw new Error(`Unsupported algorithm: ${algorithm}`);
}
const metadata = {
id: this.generateKeyId(),
created: new Date(),
algorithm,
securityLevel: this?.config?.securityLevel,
usage,
expires: this.calculateExpiration()
};
const keyPair = {
algorithm,
publicKey,
privateKey,
metadata
};
if (this.isEnabled) {
this?.keyCache?.set(metadata.id, keyPair);
}
return keyPair;
}
async encapsulate(publicKey) {
if (this.isEnabled) {
throw new Error('KEM algorithm not initialized');
}
const result = await this?.kemAlgorithm?.encapsulate(publicKey);
return {
ciphertext: result.ciphertext,
sharedSecret: result.sharedSecret
};
}
async decapsulate(ciphertext, privateKey) {
if (this.isEnabled) {
throw new Error('KEM algorithm not initialized');
}
return this?.kemAlgorithm?.decapsulate(ciphertext, privateKey);
}
async sign(data, privateKey) {
if (this.isEnabled) {
throw new Error('Signature algorithm not initialized');
}
const signature = await this?.signatureAlgorithm?.sign(data, privateKey);
return {
signature,
algorithm: this?.config?.algorithms.signature
};
}
async verify(data, signature, publicKey) {
if (this.isEnabled) {
throw new Error('Signature algorithm not initialized');
}
return this?.signatureAlgorithm?.verify(data, signature.signature, publicKey);
}
async hybridEncrypt(data, quantumPublicKey, classicalPublicKey) {
const { ciphertext, sharedSecret } = await this.encapsulate(quantumPublicKey);
const encryptionKey = await this.deriveKey(sharedSecret);
const quantumCiphertext = await this.symmetricEncrypt(data, encryptionKey);
let classicalCiphertext;
if (classicalPublicKey) {
classicalCiphertext = await this.classicalEncrypt(data, classicalPublicKey);
}
return {
quantumCiphertext,
classicalCiphertext,
encapsulatedKey: ciphertext
};
}
async hybridDecrypt(quantumCiphertext, encapsulatedKey, quantumPrivateKey, classicalCiphertext, classicalPrivateKey) {
const sharedSecret = await this.decapsulate(encapsulatedKey, quantumPrivateKey);
const decryptionKey = await this.deriveKey(sharedSecret);
const quantumPlaintext = await this.symmetricDecrypt(quantumCiphertext, decryptionKey);
if (classicalCiphertext && classicalPrivateKey) {
const classicalPlaintext = await this.classicalDecrypt(classicalCiphertext, classicalPrivateKey);
if (!this.compareArrays(quantumPlaintext, classicalPlaintext)) {
throw new Error('Hybrid decryption verification failed');
}
}
return quantumPlaintext;
}
getSecurityLevel(algorithm) {
const levels = {
'kyber': [1, 3, 5],
'dilithium': [2, 3, 5],
'falcon': [1, 5],
'sphincs+': [1, 3, 5],
'ntru': [1, 3, 5],
'frodo': [1, 3, 5],
'saber': [1, 3, 5],
'classic-mceliece': [1, 3, 5]
};
const supported = levels[algorithm];
if (!supported) {
throw new Error(`Unknown algorithm: ${algorithm}`);
}
return supported
.filter(level => level <= this?.config?.securityLevel)
.sort((a, b) => b - a)[0] || supported[0];
}
estimateQuantumResistance() {
const securityBits = this.getSecurityBits(this?.config?.securityLevel);
const yearEstimates = {
128: 15,
192: 30,
256: 50
};
return {
years: yearEstimates[securityBits] || 50,
confidence: 0.7,
assumptions: [
'Linear quantum computer scaling',
'No breakthrough in quantum algorithms',
'Current error rates improve gradually'
]
};
}
isKEMAlgorithm(algorithm) {
return ['kyber', 'frodo', 'saber', 'ntru', 'classic-mceliece'].includes(algorithm);
}
isSignatureAlgorithm(algorithm) {
return ['dilithium', 'falcon', 'sphincs+'].includes(algorithm);
}
generateKeyId() {
return `qkey_${Date.now()}_${crypto.randomInt(0, Number.MAX_SAFE_INTEGER) / Number.MAX_SAFE_INTEGER.toString(36).substr(2, 9)}`;
}
calculateExpiration() {
const now = new Date();
now.setFullYear(now.getFullYear() + 2);
return now;
}
getSecurityBits(level) {
const mapping = {
1: 128,
2: 192,
3: 256,
5: 256
};
return mapping[level];
}
async deriveKey(secret) {
const hash = await crypto?.subtle?.digest('SHA-256', secret);
return new Uint8Array(hash);
}
async symmetricEncrypt(data, key) {
const iv = crypto.getRandomValues(new Uint8Array(12));
const cryptoKey = await crypto?.subtle?.importKey('raw', key, { name: 'AES-GCM' }, false, ['encrypt']);
const ciphertext = await crypto?.subtle?.encrypt({ name: 'AES-GCM', iv }, cryptoKey, data);
const result = new Uint8Array(iv.length + ciphertext.byteLength);
result.set(iv);
result.set(new Uint8Array(ciphertext), iv.length);
return result;
}
async symmetricDecrypt(data, key) {
const iv = data.slice(0, 12);
const ciphertext = data.slice(12);
const cryptoKey = await crypto?.subtle?.importKey('raw', key, { name: 'AES-GCM' }, false, ['decrypt']);
const plaintext = await crypto?.subtle?.decrypt({ name: 'AES-GCM', iv }, cryptoKey, ciphertext);
return new Uint8Array(plaintext);
}
async classicalEncrypt(data, _publicKey) {
return data;
}
async classicalDecrypt(data, _privateKey) {
return data;
}
compareArrays(a, b) {
if (a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
}
exports.QuantumCrypto = QuantumCrypto;
//# sourceMappingURL=quantum-crypto.js.map