> For the complete documentation index, see [llms.txt](https://quantumwing.gitbook.io/quantumwing/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://quantumwing.gitbook.io/quantumwing/cryptography/quantum-safe-crypto.md).

# Quantum-Safe Crypto

## Overview

QuantumWing implements **post-quantum cryptography (PQC)** to protect against attacks from future **quantum computers**, which can break traditional cryptographic algorithms like RSA, ECDSA, and Ed25519 using **Shor's algorithm**.

**Key Features:**

* **NIST-Approved PQC**: Using standardized post-quantum algorithms (Dilithium, SHA3)
* **Dilithium Digital Signatures**: Module-LWE lattice-based signatures (NIST FIPS 204)
* **SHA3-256 Hashing**: Quantum-resistant hash function (NIST FIPS 202)
* **Mode 2/3/5 Support**: Three security levels (128-bit, 192-bit, 256-bit)
* **Cloudflare CIRCL Library**: Production-grade implementation
* **Zero Classical Vulnerabilities**: No RSA, ECDSA, or Ed25519 exposure

**Why Quantum-Safe?**

* **Quantum Threat Timeline**: Large-scale quantum computers expected by 2030-2040
* **Store-Now-Decrypt-Later**: Attackers can record encrypted data now, decrypt later with quantum computers
* **Long-Term Value Protection**: Blockchain data must remain secure for decades
* **Future-Proof**: Transition to quantum-safe cryptography before quantum computers exist

***

## Quantum Computing Threat

### 1. Shor's Algorithm (Factorization)

**Target**: RSA, ECDSA, EdDSA, Diffie-Hellman (all based on integer factorization or discrete logarithm).

**Attack**:

* Quantum computer with **\~4000 qubits** can break **2048-bit RSA** in hours
* Quantum computer with **\~1500 qubits** can break **256-bit ECDSA** in minutes

**Impact on Traditional Blockchains:**

```
Bitcoin (ECDSA secp256k1):
- Public key exposed in P2PKH addresses
- Quantum computer derives private key from public key
- Attacker steals funds from any address with known public key

Ethereum (ECDSA secp256k1):
- All addresses expose public keys after first transaction
- Quantum computer breaks all existing accounts
- Total value at risk: $200+ billion
```

***

### 2. Grover's Algorithm (Search)

**Target**: Symmetric encryption (AES), hash functions (SHA-256).

**Attack**:

* Grover's algorithm provides **quadratic speedup** for brute-force search
* 256-bit key → effective 128-bit security against quantum computers
* SHA-256 collision resistance: 256-bit → 128-bit effective

**Impact on Hash Functions:**

```
SHA-256 (Classical Security):
- Pre-image resistance: 2^256 operations
- Collision resistance: 2^128 operations

SHA-256 (Quantum Security):
- Pre-image resistance: 2^128 operations (Grover)
- Collision resistance: 2^64 operations (Grover)

Solution: Use SHA3-256 (Keccak) with 256-bit output
- Pre-image resistance: 2^256 operations (Grover-resistant)
- Collision resistance: 2^128 operations (sufficient for blockchain)
```

***

### 3. Store-Now-Decrypt-Later (SNDL)

**Attack Scenario:**

1. Attacker records encrypted blockchain transactions today (2025)
2. Attacker waits for large-scale quantum computer (2035)
3. Attacker decrypts historical transactions, extracts private keys
4. Attacker steals funds from wallets that were secure in 2025

**Real-World Risk:**

* **Nation-state actors** already harvesting encrypted data
* **Long-term blockchain security** requires quantum-resistance NOW
* **Transition period**: 5-10 years to migrate all users to quantum-safe systems

**QuantumWing Protection:**

* All signatures use **Dilithium Mode 3** (quantum-resistant)
* No RSA/ECDSA exposure (immune to SNDL attacks)
* Private keys never exposed (Dilithium public keys cannot derive private keys with quantum computers)

***

## NIST Post-Quantum Cryptography Standards

### Overview

In **August 2024**, NIST (National Institute of Standards and Technology) published **final standards** for post-quantum cryptography:

| **Algorithm**          | **Type**          | **NIST Standard** | **Security**       | **Status**         |
| ---------------------- | ----------------- | ----------------- | ------------------ | ------------------ |
| **Dilithium (ML-DSA)** | Digital Signature | FIPS 204          | Module-LWE lattice | ✅ **STANDARDIZED** |
| **Kyber (ML-KEM)**     | Key Encapsulation | FIPS 203          | Module-LWE lattice | ✅ **STANDARDIZED** |
| **SPHINCS+**           | Digital Signature | FIPS 205          | Hash-based         | ✅ **STANDARDIZED** |
| **Falcon**             | Digital Signature | (Backup)          | NTRU lattice       | 🟡 **ALTERNATIVE** |

**QuantumWing Uses**:

* ✅ **Dilithium Mode 3** for all digital signatures (blocks, transactions, attestations)
* ✅ **Kyber-1024** for key encapsulation (encrypted communication, NIST Level 5)
* ✅ **SHA3-256** for all hashing (Keccak family, quantum-resistant)
* ❌ **SPHINCS+** not used (stateless but larger signatures: 16-50 KB vs Dilithium 3.3 KB)

***

### Dilithium (ML-DSA) - Digital Signatures

**Algorithm**: Module Learning With Errors (Module-LWE) lattice-based signature scheme.

**Security Basis**: Hardness of finding short vectors in lattices (quantum-resistant problem).

**Key Sizes**:

```
Dilithium Mode 2 (NIST Level 1):
- Private Key: 2,528 bytes
- Public Key:  1,312 bytes
- Signature:   2,420 bytes
- Security:    128-bit (equivalent to AES-128)

Dilithium Mode 3 (NIST Level 3) ← QuantumWing Uses This
- Private Key: 4,000 bytes
- Public Key:  1,952 bytes
- Signature:   3,293 bytes
- Security:    192-bit (equivalent to AES-192)

Dilithium Mode 5 (NIST Level 5):
- Private Key: 4,864 bytes
- Public Key:  2,592 bytes
- Signature:   4,595 bytes
- Security:    256-bit (equivalent to AES-256)
```

**Why Mode 3?**

* **Balanced Security/Performance**: 192-bit security sufficient for next 50+ years
* **Reasonable Signature Size**: 3,293 bytes (vs Mode 5: 4,595 bytes)
* **NIST Recommended**: Mode 3 is default for most applications
* **Future-Proof**: Survives even optimistic quantum computing advances

**Performance (Cloudflare CIRCL)**:

```
Key Generation: ~0.5-1 ms
Signing:        ~1-2 ms
Verification:   ~0.5-2 ms

(On modern CPU: Intel Xeon, ARM64)
```

***

### Kyber (ML-KEM) - Key Encapsulation

**Algorithm**: Module Learning With Errors (Module-LWE) lattice-based KEM.

**Use Case**: Encrypt symmetric keys for confidential transactions, encrypted smart contract state.

**Key Sizes**:

```
Kyber-512 (NIST Level 1):
- Public Key:   800 bytes
- Ciphertext:   768 bytes
- Shared Secret: 32 bytes
- Security:     128-bit

Kyber-768 (NIST Level 3):
- Public Key:   1,184 bytes
- Ciphertext:   1,088 bytes
- Shared Secret: 32 bytes
- Security:     192-bit

Kyber-1024 (NIST Level 5):
- Public Key:   1,568 bytes
- Ciphertext:   1,568 bytes
- Shared Secret: 32 bytes
- Security:     256-bit
```

**Status in QuantumWing**: ✅ **PRODUCTION-READY** — Kyber-1024 (ML-KEM, FIPS 203) is implemented in `crypto/kyber/` and integrated into the P2P layer for quantum-safe encrypted node-to-node messaging (Kyber + AES-256-GCM hybrid). See [Kyber-1024 Key Encapsulation](/quantumwing/cryptography/kyber.md).

**Current & Future Use Cases**:

* ✅ Encrypted P2P messaging (checkpoints, blocks, transactions over libp2p)
* 🚧 Encrypted transaction amounts (like Zcash/Monero with quantum-safe KEM)
* 🚧 Confidential smart contract execution (encrypted inputs/outputs)
* 🚧 Quantum-safe TLS for P2P networking (Kyber key exchange)

***

## QuantumWing Cryptographic Primitives

### 1. Digital Signatures (Dilithium Mode 3)

**Usage**:

* ✅ Block headers (validator signs canonical header)
* ✅ Transactions (user signs transaction hash)
* ✅ Attestations (validator votes on blocks)
* ✅ VRF proofs (validator selection)
* ✅ RANDAO commits/reveals (randomness generation)

**Implementation**:

```go
import "github.com/cloudflare/circl/sign/dilithium/mode3"

// Generate keypair
publicKey, privateKey, err := mode3.GenerateKey(rand.Reader)

// Sign message
message := []byte("block header hash")
signature, err := privateKey.Sign(rand.Reader, message, crypto.Hash(0))

// Verify signature
valid := mode3.Verify(&publicKey, message, signature)
```

**Signature Structure**:

```go
type Signature struct {
    Mode      Mode      // Mode3 (192-bit security)
    Signature []byte    // 3,293 bytes (Dilithium signature)
    PublicKey []byte    // 1,952 bytes (Dilithium public key)
    Message   []byte    // Original message (for verification)
    Timestamp time.Time // When signature was created
}
```

***

### 2. Hash Functions (SHA3-256)

**Usage**:

* ✅ Block hashing (chain integrity)
* ✅ Transaction hashing (merkle trees)
* ✅ Address derivation (public key → address)
* ✅ VRF seed generation (randomness)
* ✅ RANDAO commits (commitment scheme)

**Why SHA3 Instead of SHA2?**

* **Quantum Resistance**: SHA3 (Keccak) has stronger quantum resistance than SHA-256
* **NIST Standard**: FIPS 202 (2015)
* **Larger State**: 1600-bit internal state (vs SHA-256: 512-bit)
* **Sponge Construction**: Resists length-extension attacks

**Implementation**:

```go
import "golang.org/x/crypto/sha3"

// SHA3-256 hash
data := []byte("block header")
hash := sha3.Sum256(data)  // 32-byte output

// Keccak-256 hash (for VRF seed generation)
import "github.com/ethereum/go-ethereum/crypto"
hash := crypto.Keccak256(data)  // 32-byte output
```

**Hash Comparison**:

```
SHA-256 (Classical):
- Pre-image: 2^256 operations
- Collision: 2^128 operations
- Quantum:   2^128 / 2^64 (Grover)

SHA3-256 (Keccak):
- Pre-image: 2^256 operations
- Collision: 2^128 operations
- Quantum:   2^256 / 2^128 (Grover-resistant due to sponge)
```

***

### 3. Key Derivation (BIP-39 + Dilithium)

**Usage**:

* ✅ Wallet seed generation (24-word mnemonic)
* ✅ Hierarchical deterministic keys (BIP-44 compatible)
* ✅ Multi-account support (account index in derivation path)

**Derivation Path**:

```
m / 44' / 9999' / account' / change / index

44'    = BIP-44 standard
9999'  = QuantumWing coin type (registered)
account' = Account index (0, 1, 2, ...)
change = 0 (external), 1 (internal)
index  = Address index (0, 1, 2, ...)
```

**Implementation**:

```go
import "github.com/tyler-smith/go-bip39"

// Generate mnemonic
entropy, _ := bip39.NewEntropy(256)  // 256-bit entropy
mnemonic, _ := bip39.NewMnemonic(entropy)  // 24 words

// Derive seed
seed := bip39.NewSeed(mnemonic, "passphrase")  // 512-bit seed

// Derive Dilithium keypair
privateKey := deriveDilithiumKey(seed, "m/44'/9999'/0'/0/0")
publicKey := privateKey.PublicKey()
```

**Note**: BIP-39 mnemonics are **quantum-safe** (256-bit entropy). Derived Dilithium keys inherit quantum resistance.

***

### 4. Address Generation

**Formula**:

```
Address = 0x || Keccak256(Dilithium_PublicKey)[12:]

Steps:
1. Generate Dilithium Mode 3 public key (1,952 bytes)
2. Hash public key with Keccak-256 (32 bytes)
3. Take last 20 bytes (160 bits)
4. Prefix with 0x

Result: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1
```

**Why Keccak-256?**

* **EVM Compatibility**: Ethereum-style addresses (20 bytes)
* **Quantum Resistance**: Keccak-256 is quantum-resistant hash function
* **Collision Resistance**: 2^160 addresses (sufficient for blockchain scale)

**Example**:

```go
import "golang.org/x/crypto/sha3"

// Dilithium public key (1,952 bytes)
publicKey := []byte{...}

// Keccak-256 hash
hash := sha3.NewLegacyKeccak256()
hash.Write(publicKey)
fullHash := hash.Sum(nil)  // 32 bytes

// Take last 20 bytes
address := fullHash[12:]  // 20-byte address

// Format as hex
addressHex := "0x" + hex.EncodeToString(address)
// Result: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1
```

***

## Security Levels Explained

### NIST Security Levels

| **Level**   | **Classical Security** | **Quantum Security** | **Equivalent** | **Use Case**              |
| ----------- | ---------------------- | -------------------- | -------------- | ------------------------- |
| **Level 1** | 128-bit                | 64-bit (Grover)      | AES-128        | Short-term (5-10 years)   |
| **Level 3** | 192-bit                | 96-bit (Grover)      | AES-192        | Medium-term (20-30 years) |
| **Level 5** | 256-bit                | 128-bit (Grover)     | AES-256        | Long-term (50+ years)     |

**Grover's Algorithm Impact**:

* Quantum computers provide **quadratic speedup** for brute-force search
* 256-bit classical security → 128-bit quantum security
* To maintain 128-bit security against quantum: use 256-bit keys

**QuantumWing Choice (Mode 3 = Level 3)**:

* **192-bit classical security** → **96-bit quantum security**
* Sufficient for next 30+ years (even with optimistic quantum progress)
* Balanced performance/security (Mode 5 is overkill for blockchain)

***

### Attack Cost Comparison

**Breaking Different Signature Schemes**:

| **Scheme**           | **Classical Attack** | **Quantum Attack**            | **Attack Cost**     |
| -------------------- | -------------------- | ----------------------------- | ------------------- |
| **RSA-2048**         | 2^112 operations     | 2^30 operations (Shor)        | $1 million (2035)   |
| **ECDSA-256**        | 2^128 operations     | 2^20 operations (Shor)        | $10,000 (2035)      |
| **Dilithium Mode 2** | 2^128 operations     | 2^128 operations (No speedup) | $10^38 (Impossible) |
| **Dilithium Mode 3** | 2^192 operations     | 2^192 operations (No speedup) | $10^58 (Impossible) |
| **Dilithium Mode 5** | 2^256 operations     | 2^256 operations (No speedup) | $10^77 (Impossible) |

**Key Insight**: Lattice-based cryptography (Dilithium) has **no known quantum speedup**. Grover's algorithm does NOT apply to Module-LWE problem.

***

## Performance Characteristics

### 1. Signature Generation Time

**Benchmarks (Intel Xeon E5-2680 v4, single-core)**:

```
Algorithm          | Key Gen | Sign  | Verify | Signature Size
-------------------|---------|-------|--------|---------------
RSA-2048           | 500ms   | 5ms   | 0.1ms  | 256 bytes
ECDSA-256          | 0.5ms   | 1ms   | 2ms    | 64 bytes
Ed25519            | 0.05ms  | 0.05ms| 0.1ms  | 64 bytes
Dilithium Mode 2   | 0.5ms   | 1ms   | 0.5ms  | 2,420 bytes
Dilithium Mode 3   | 1ms     | 2ms   | 1ms    | 3,293 bytes
Dilithium Mode 5   | 1.5ms   | 3ms   | 2ms    | 4,595 bytes
```

**QuantumWing Performance (Mode 3)**:

* **Block Signing**: \~2ms (acceptable for 12-second slots)
* **Transaction Signing**: \~2ms (negligible for user experience)
* **Attestation Verification**: \~1ms (19ms for 10 validators per epoch)

***

### 2. Signature Size Overhead

**Storage Overhead**:

```
Classical Blockchain (ECDSA):
- Signature: 64 bytes
- Public key: 33 bytes (compressed)
- Total: 97 bytes per signature

QuantumWing (Dilithium Mode 3):
- Signature: 3,293 bytes
- Public key: 1,952 bytes
- Total: 5,245 bytes per signature

Overhead: 5,245 / 97 = 54× larger

Annual Storage (1M transactions/day):
- ECDSA: 97 bytes × 1M × 365 = 35.4 GB/year
- Dilithium: 5,245 bytes × 1M × 365 = 1,914 GB/year
- Difference: 1,878 GB/year (acceptable with modern storage)
```

**Mitigation Strategies**:

* ✅ **Signature Pruning**: Remove signatures after finality (keep only last 10 epochs)
* ✅ **State Snapshots**: Archive old signatures off-chain
* ✅ **Compression**: zstd compression reduces Dilithium signatures by \~20%
* 🚧 **BLS-like Aggregation**: Future research (aggregate multiple Dilithium signatures)

***

### 3. Verification Throughput

**Parallel Verification (8-core CPU)**:

```
Single-threaded:
- 1,000 signatures/second (1ms per signature)

8 cores (parallel):
- 8,000 signatures/second

1,000 TPS blockchain:
- Verification time: 1,000 / 8,000 = 0.125 seconds (125ms per block)
- Block time: 12 seconds
- Verification overhead: 125ms / 12,000ms = 1.04%

Conclusion: Dilithium Mode 3 verification is NOT a bottleneck.
```

***

## Quantum Resistance Comparison

### QuantumWing vs Traditional Blockchains

| **Feature**                 | **Bitcoin**          | **Ethereum**       | **QuantumWing**       |
| --------------------------- | -------------------- | ------------------ | --------------------- |
| **Signature Algorithm**     | ECDSA secp256k1      | ECDSA secp256k1    | Dilithium Mode 3      |
| **Hash Function**           | SHA-256 (double)     | Keccak-256         | SHA3-256              |
| **Quantum-Safe Signatures** | ❌ No                 | ❌ No               | ✅ Yes                 |
| **Quantum-Safe Hashing**    | ⚠️ Partial (SHA-256) | ✅ Yes (Keccak-256) | ✅ Yes (SHA3-256)      |
| **Post-Quantum KEM**        | ❌ No                 | ❌ No               | ✅ Yes (Kyber-1024)    |
| **Grover Resistance**       | ⚠️ 128-bit effective | ✅ 256-bit          | ✅ 256-bit             |
| **Shor Resistance**         | ❌ Vulnerable         | ❌ Vulnerable       | ✅ Resistant           |
| **NIST Standard**           | ❌ Pre-quantum        | ❌ Pre-quantum      | ✅ FIPS 203 + FIPS 204 |
| **Signature Size**          | 64 bytes             | 64 bytes           | 3,293 bytes           |
| **Verification Time**       | 0.1ms                | 0.1ms              | 1ms                   |

**Key Takeaway**: QuantumWing is **fully quantum-resistant** TODAY (2025), while Bitcoin/Ethereum will require **hard forks** to migrate to post-quantum cryptography.

***

### Migration Cost for Traditional Blockchains

**Bitcoin Quantum Migration Scenario (2030)**:

1. **Hard Fork Required**: All nodes must upgrade to Dilithium signatures
2. **Address Migration**: All users must move funds to new quantum-safe addresses
3. **Lost Funds**: \~4M BTC in early addresses (no owner to migrate) permanently locked
4. **Network Split**: Nodes refusing to upgrade (chain split risk)
5. **Value Drop**: Market panic, price volatility
6. **Time to Complete**: 2-5 years (slow adoption)

**QuantumWing Advantage**:

* ✅ **Already Quantum-Safe**: No migration needed
* ✅ **Future-Proof**: Can operate securely even after large-scale quantum computers exist
* ✅ **No Hard Fork Risk**: All validators already use Dilithium Mode 3

***

## Code Examples

### 1. Generate Dilithium Keypair

```go
package main

import (
    "fmt"
    "github.com/dolfrin/QuantumWing/crypto/dilithium"
)

func main() {
    // Generate Dilithium Mode 3 keypair
    mode := dilithium.Mode3
    keyPair, err := dilithium.GenerateKeyPair(mode)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Mode: %s\n", keyPair.Mode)
    fmt.Printf("Private Key Size: %d bytes\n", len(keyPair.PrivateKey))
    fmt.Printf("Public Key Size: %d bytes\n", len(keyPair.PublicKey))
    fmt.Printf("Generated: %s\n", keyPair.Generated)
    
    // Output:
    // Mode: dilithium3
    // Private Key Size: 4000 bytes
    // Public Key Size: 1952 bytes
    // Generated: 2025-10-28 12:34:56
}
```

***

### 2. Sign and Verify Message

```go
package main

import (
    "fmt"
    "github.com/dolfrin/QuantumWing/crypto/dilithium"
)

func main() {
    // Generate keypair
    mode := dilithium.Mode3
    keyPair, _ := dilithium.GenerateKeyPair(mode)
    
    // Create signer
    signer := dilithium.NewSigner(keyPair)
    
    // Sign message
    message := []byte("QuantumWing transaction")
    signature, err := signer.Sign(message)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Signature Size: %d bytes\n", len(signature.Signature))
    fmt.Printf("Signature Mode: %s\n", signature.Mode)
    
    // Verify signature
    result := signature.Verify()
    
    if result.Valid {
        fmt.Printf("✅ Signature VALID (verified in %s)\n", result.Duration)
    } else {
        fmt.Printf("❌ Signature INVALID: %s\n", result.Error)
    }
    
    // Output:
    // Signature Size: 3293 bytes
    // Signature Mode: dilithium3
    // ✅ Signature VALID (verified in 1.2ms)
}
```

***

### 3. Derive Address from Public Key

```go
package main

import (
    "encoding/hex"
    "fmt"
    "golang.org/x/crypto/sha3"
    "github.com/dolfrin/QuantumWing/crypto/dilithium"
)

func deriveAddress(publicKey []byte) string {
    // Keccak-256 hash
    hash := sha3.NewLegacyKeccak256()
    hash.Write(publicKey)
    fullHash := hash.Sum(nil)  // 32 bytes
    
    // Take last 20 bytes
    address := fullHash[12:]
    
    // Format as hex
    return "0x" + hex.EncodeToString(address)
}

func main() {
    // Generate Dilithium keypair
    keyPair, _ := dilithium.GenerateKeyPair(dilithium.Mode3)
    
    // Derive address
    address := deriveAddress(keyPair.PublicKey)
    
    fmt.Printf("Public Key Size: %d bytes\n", len(keyPair.PublicKey))
    fmt.Printf("Address: %s\n", address)
    
    // Output:
    // Public Key Size: 1952 bytes
    // Address: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1
}
```

***

### 4. Batch Sign Multiple Messages

```go
package main

import (
    "fmt"
    "github.com/dolfrin/QuantumWing/crypto/dilithium"
)

func main() {
    // Generate keypair
    keyPair, _ := dilithium.GenerateKeyPair(dilithium.Mode3)
    signer := dilithium.NewSigner(keyPair)
    
    // Create 100 messages
    messages := make([][]byte, 100)
    for i := 0; i < 100; i++ {
        messages[i] = []byte(fmt.Sprintf("Transaction %d", i))
    }
    
    // Batch sign
    signatures, err := signer.BatchSign(messages)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Signed %d messages\n", len(signatures))
    
    // Batch verify
    results := signer.BatchVerify(signatures)
    
    validCount := 0
    for _, result := range results {
        if result.Valid {
            validCount++
        }
    }
    
    fmt.Printf("Valid signatures: %d / %d\n", validCount, len(results))
    
    // Output:
    // Signed 100 messages
    // Valid signatures: 100 / 100
}
```

***

## Security Best Practices

### 1. Key Generation

✅ **DO:**

* Use **cryptographically secure random number generator** (`crypto/rand`)
* Generate keys with **Dilithium Mode 3** (192-bit security minimum)
* Store private keys in **encrypted keystore** (AES-256-GCM)
* Use **BIP-39 mnemonics** for wallet seed backup (24 words)
* Implement **hardware security modules (HSM)** for validator keys

❌ **DON'T:**

* Use predictable random number generators (`math/rand`)
* Generate keys with Mode 2 for production (128-bit security insufficient)
* Store private keys in plaintext files
* Share private keys between validators (single point of failure)
* Use same key for multiple purposes (signing, encryption)

***

### 2. Signature Verification

✅ **DO:**

* **Always verify** Dilithium signatures before accepting blocks/transactions
* Check signature **mode matches expected** (Mode 3 for QuantumWing)
* Verify signature **size is correct** (3,293 bytes for Mode 3)
* Use **canonical message format** for signing (deterministic serialization)
* Implement **replay attack protection** (include timestamp, nonce)

❌ **DON'T:**

* Trust signatures without verification (security risk)
* Accept signatures with wrong mode (Mode 2 signatures in Mode 3 chain)
* Skip signature size validation (malformed signatures)
* Use non-deterministic message serialization (signature mismatch)
* Reuse signatures across different contexts (signature malleability)

***

### 3. Key Storage

✅ **DO:**

* Encrypt private keys with **AES-256-GCM** and user password
* Use **scrypt** or **argon2** for password-based key derivation
* Store encrypted keys in **separate file** from public keys
* Implement **key rotation** for long-lived validators
* Backup encrypted keys to **offline storage** (cold storage)

❌ **DON'T:**

* Store private keys in plaintext (compromise risk)
* Use weak passwords (brute-force attack)
* Store keys in version control (Git commits)
* Share keys via insecure channels (email, Slack)
* Store keys on cloud servers without encryption

***

## Future Roadmap

### 1. Hybrid Cryptography (Research)

**Concept**: Combine classical + post-quantum algorithms for defense-in-depth.

**Example**:

```go
// Hybrid signature: ECDSA + Dilithium
hybridSignature := {
    ECDSASignature:     Sign_ECDSA(message),
    DilithiumSignature: Sign_Dilithium(message),
}

// Verify: BOTH must be valid
valid := Verify_ECDSA(hybridSignature.ECDSA) && 
         Verify_Dilithium(hybridSignature.Dilithium)
```

**Advantage**: Protection even if ONE algorithm is broken (quantum or classical attack).

***

### 2. Signature Aggregation (Research)

**Goal**: Aggregate multiple Dilithium signatures into single signature (like BLS).

**Challenge**: No known lattice-based signature aggregation scheme exists.

**Current Research**:

* **Approximate Aggregation**: Aggregate with small error probability
* **Merkle Tree Aggregation**: Use Merkle tree root as aggregate signature
* **Threshold Signatures**: Distribute signing power across multiple validators

**Impact**: Reduce attestation storage from 5.3 KB/validator to \~100 bytes/aggregate.

***

## Conclusion

QuantumWing's **quantum-safe cryptography** provides:

✅ **Full Quantum Resistance** (Dilithium Mode 3 signatures, SHA3-256 hashing)\
✅ **NIST Standardized** (FIPS 204, FIPS 202)\
✅ **Production-Ready** (Cloudflare CIRCL library)\
✅ **Future-Proof** (secure for next 50+ years)\
✅ **No Migration Risk** (already quantum-safe TODAY)

**Trade-offs**:

* ⚠️ **Larger Signatures** (3,293 bytes vs 64 bytes ECDSA)
* ⚠️ **Slower Verification** (1-2ms vs 0.1ms Ed25519)
* ✅ **Acceptable Overhead** (\~1% of block time for verification)

**Next Steps:**

* ✅ **Kyber KEM** shipped — Kyber-1024 powers encrypted P2P messaging (`crypto/kyber/`)
* Extend Kyber to **encrypted transaction amounts** (confidential transactions)
* Research **signature aggregation** for reduced storage
* Deploy **quantum-safe TLS** for P2P networking
* Monitor **NIST updates** for new post-quantum standards

**Current Status**: ✅ **PRODUCTION-READY** - All signatures quantum-safe, hash functions quantum-resistant, no classical cryptography vulnerabilities.

***

**Related Documentation:**

* [Dilithium Signatures](/quantumwing/cryptography/dilithium.md) - Detailed Dilithium implementation
* [Key Derivation](/quantumwing/cryptography/key-derivation.md) - BIP-39/BIP-44 wallet key derivation
* [Address Generation](/quantumwing/cryptography/addresses.md) - Dilithium public key → EVM address
* [Transaction Signing](/quantumwing/transactions/signing.md) - Sign transactions with Dilithium


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://quantumwing.gitbook.io/quantumwing/cryptography/quantum-safe-crypto.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
