Crate qsfs_core

Crate qsfs_core 

Source
Expand description

Β§qsfs-core: Quantum-Shield File System Core Library

Crates.io Documentation License

The world’s most comprehensive post-quantum file encryption library with complete cryptographic suite

This crate provides the core cryptographic primitives and file format implementation for QSFS, a quantum-resistant file encryption system that implements NIST-standardized post-quantum cryptography with ML-DSA-87 digital signatures and a complete suite of encryption technologies.

Β§πŸ›‘οΈ Complete Cryptographic Arsenal

Β§Post-Quantum Cryptography (CNSA 2.0 Compliant)

  • ML-KEM-1024 (FIPS 203) - Quantum-resistant key encapsulation, NIST Level 5 security
  • ML-DSA-87 (FIPS 204) - Post-quantum digital signatures, NIST Level 5 security
  • CNSA 2.0 Compliant - Meets NSA Commercial National Security Algorithm Suite requirements

Β§Hybrid Classical Cryptography

  • X25519 - Elliptic curve Diffie-Hellman key exchange for additional security layers
  • Ed25519 - EdDSA signatures for classical authentication backup

Β§Authenticated Encryption (AEAD)

  • AES-256-GCM-SIV - Nonce misuse-resistant authenticated encryption (default)
  • AES-256-GCM - Standard authenticated encryption with additional data
  • ChaCha20-Poly1305 - Stream cipher with Poly1305 MAC for cascade encryption

Β§Key Derivation & Hashing

  • HKDF-SHA3-384 - Key derivation with enhanced domain separation
  • BLAKE3 - High-performance cryptographic hashing for file integrity
  • Argon2 - Memory-hard key derivation for password-based encryption

Β§Hardware Security Module (HSM) Support

  • PKCS#11 - Hardware security module integration via cryptoki
  • Hardware acceleration - Optimized primitives using available CPU instructions

Β§Memory Safety & Security

  • Automatic zeroization - Secure memory clearing using zeroize crate
  • Constant-time operations - Side-channel attack resistance
  • Memory locking - Prevents sensitive data from being swapped to disk
  • Secure permissions - Atomic file operations with restricted access

Β§πŸš€ Quick Start

Add this to your Cargo.toml:

[dependencies]
qsfs-core = { version = "0.1.2", features = ["pq", "hybrid-x25519", "gcm-siv", "cascade", "hsm"] }

Β§Basic Encryption with All Technologies

use qsfs_core::{seal, unseal, SealRequest, UnsealContext, Signer};
use tokio::fs::File;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Generate or load cryptographic keys
    let ml_kem_pk = /* load ML-KEM-1024 public key */;
    let x25519_pk = /* load X25519 public key */;
    let signer = Signer::generate()?; // ML-DSA-87 signer

    // Encrypt with complete quantum-resistant suite
    let request = SealRequest {
        input_path: "sensitive-document.pdf",
        recipients: vec![(
            "alice".to_string(),
            ml_kem_pk,
            x25519_pk,
        )],
        header_sign_mldsa_sk: None,
        chunk_size: 131072, // 128KB chunks for streaming
        signer: Some(&signer), // ML-DSA-87 signatures
    };

    // Seal with all encryption technologies
    seal(request, "document.qsfs").await?;

    // Decrypt with signature verification
    let input = File::open("document.qsfs").await?;
    let context = UnsealContext {
        mlkem_sk: &ml_kem_sk,
        x25519_sk: Some(x25519_sk),
        allow_unsigned: false, // Require signatures
        trust_any_signer: false, // Use trust store
    };

    unseal(input, "decrypted.pdf", context).await?;
    println!("βœ… File decrypted and signature verified!");

    Ok(())
}

Β§πŸ”§ Feature Flags

Enable specific cryptographic technologies:

[dependencies]
qsfs-core = { version = "0.1.2", features = [
    "pq",           # Post-quantum: ML-KEM-1024 + ML-DSA-87
    "hybrid-x25519", # Hybrid: X25519 + Ed25519
    "gcm-siv",      # AES-256-GCM-SIV (nonce misuse resistant)
    "gcm",          # AES-256-GCM (standard AEAD)
    "cascade",      # ChaCha20-Poly1305 cascade encryption
    "hsm",          # Hardware Security Module support
    "wasm",         # WebAssembly compatibility
] }

Β§πŸ“Š Security Specifications

ComponentAlgorithmKey SizeSecurity LevelQuantum Safe
Key EncapsulationML-KEM-10241568 bytesNIST Level 5βœ… Yes
Digital SignaturesML-DSA-874864 bytesNIST Level 5βœ… Yes
Hybrid Key ExchangeX2551932 bytes~128-bit❌ No
Symmetric EncryptionAES-256-GCM-SIV256 bits128-bitβœ… Yes
Stream CipherChaCha20-Poly1305256 bits128-bitβœ… Yes
Key DerivationHKDF-SHA3-384Variable192-bitβœ… Yes
File IntegrityBLAKE3256 bits128-bitβœ… Yes

Β§πŸ—οΈ Architecture

The library is organized into specialized modules:

  • derivation - Key derivation functions and cryptographic key management
  • [header] - File format header parsing, serialization, and metadata
  • [streaming] - Streaming AEAD for efficient large file processing
  • [security] - Memory safety, system security, and side-channel protection
  • signer - ML-DSA-87 digital signature creation and verification

Β§πŸ”’ Security Properties

Β§Quantum Resistance

  • Post-quantum algorithms protect against Shor’s algorithm (breaks RSA/ECC)
  • Large key sizes provide security against Grover’s algorithm
  • NIST standardized algorithms with extensive cryptanalysis

Β§Forward Secrecy

  • Ephemeral key exchange ensures past sessions remain secure
  • Perfect forward secrecy through ephemeral X25519 keys
  • Session isolation prevents compromise propagation

Β§Non-Repudiation

  • ML-DSA-87 signatures provide cryptographic proof of origin
  • Trust store management for signer verification
  • Canonical serialization ensures deterministic signatures

Β§Integrity Protection

  • AEAD authentication detects any tampering
  • BLAKE3 hashing for file-level integrity
  • Digital signatures for authenticity verification

§🌐 Platform Compatibility

PlatformStatusNotes
Linux x86_64βœ… Full SupportPrimary development platform
Linux ARM64βœ… Full SupportRaspberry Pi 4+ compatible
macOS Intelβœ… Full SupportHardware acceleration available
macOS Apple Siliconβœ… Full SupportNative ARM64 optimizations
Windows x64βœ… Full SupportMSVC and GNU toolchains
FreeBSD🟑 ExperimentalCommunity maintained
WebAssembly🟑 LimitedBasic functionality with wasm feature

Β§πŸ“š Examples

Β§Multi-Recipient Encryption

use qsfs_core::{seal, SealRequest, Signer};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let signer = Signer::generate()?;
     
    let request = SealRequest {
        input_path: "company-secrets.tar.gz",
        recipients: vec![
            ("alice".to_string(), alice_mlkem_pk, alice_x25519_pk),
            ("bob".to_string(), bob_mlkem_pk, bob_x25519_pk),
            ("charlie".to_string(), charlie_mlkem_pk, charlie_x25519_pk),
        ],
        header_sign_mldsa_sk: None,
        chunk_size: 262144, // 256KB chunks
        signer: Some(&signer),
    };

    seal(request, "secrets.qsfs").await?;
    println!("βœ… Encrypted for {} recipients", request.recipients.len());
    Ok(())
}

Β§HSM Integration

#[cfg(feature = "hsm")]
use qsfs_core::security::hsm;

#[cfg(feature = "hsm")]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize HSM connection
    let hsm = hsm::initialize_pkcs11("/usr/lib/libpkcs11.so")?;
     
    // Use HSM for key operations
    let key_handle = hsm.generate_key("AES", 256)?;
     
    // Encrypt using HSM-stored keys
    // ... encryption logic with HSM integration
     
    Ok(())
}

Β§πŸ”§ Advanced Configuration

Β§Custom Chunk Sizes

// Small files: 64KB chunks for lower latency
let small_file_request = SealRequest {
    chunk_size: 65536,
    // ... other fields
};

// Large files: 1MB chunks for better throughput
let large_file_request = SealRequest {
    chunk_size: 1048576,
    // ... other fields
};

Β§Algorithm Selection

use qsfs_core::suite::SuiteId;

// Force specific AEAD algorithm
let suite = SuiteId::Aes256GcmSiv; // Nonce misuse resistant
let suite = SuiteId::Aes256Gcm;    // Standard AEAD

Β§πŸ› οΈ Integration Guide

Β§Error Handling

use qsfs_core::{seal, SealRequest};
use anyhow::Result;

async fn secure_encrypt(input: &str, output: &str) -> Result<()> {
    let request = SealRequest {
        // ... configuration
    };

    match seal(request, output).await {
        Ok(()) => {
            println!("βœ… Encryption successful");
            Ok(())
        }
        Err(e) => {
            eprintln!("❌ Encryption failed: {}", e);
            Err(e)
        }
    }
}

Β§Memory Management

use qsfs_core::security::{disable_core_dumps, lock_memory};

fn secure_initialization() -> Result<(), Box<dyn std::error::Error>> {
    // Disable core dumps to prevent key leakage
    disable_core_dumps()?;
     
    // Lock sensitive memory pages
    let sensitive_data = vec![0u8; 1024];
    lock_memory(&sensitive_data)?;
     
    // ... cryptographic operations
     
    // Memory is automatically zeroized on drop
    Ok(())
}

Β§πŸ“– Further Reading

Re-exportsΒ§

pub use signer::Signer;
pub use signer::TrustStore;
pub use signer::verify_signature;
pub use signer::default_trustdb_path;
pub use signer::auto_provision_signer;
pub use canonical::CanonicalHeader;
pub use canonical::SignatureMetadata as CanonicalSignatureMetadata;

ModulesΒ§

canonical
derivation
pae
signer
suite

StructsΒ§

Header
RecipientEntry
SealRequest
SignatureMetadata
UnsealContext

FunctionsΒ§

seal
unseal