pqc-binary-format 1.0.12

Standardized binary format for post-quantum cryptography encrypted data interchange
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# PQC Binary Format v1.0.12

[![Crates.io](https://img.shields.io/crates/v/pqc-binary-format.svg)](https://crates.io/crates/pqc-binary-format)
[![Documentation](https://docs.rs/pqc-binary-format/badge.svg)](https://docs.rs/pqc-binary-format)
[![License](https://img.shields.io/crates/l/pqc-binary-format.svg)](LICENSE-MIT)
[![Build Status](https://github.com/PQCrypta/pqcrypta-community/workflows/CI/badge.svg)](https://github.com/PQCrypta/pqcrypta-community/actions)

**A standardized, self-describing binary format for post-quantum cryptography encrypted data interchange.**

## ๐ŸŒŸ The Problem

Post-quantum cryptography (PQC) implementations suffer from the "Babel Tower problem": different implementations cannot interoperate because there is no standardized format for encrypted data. Each library uses its own proprietary format, making cross-platform and cross-language encryption impossible.

## ๐Ÿ’ก The Solution

PQC Binary Format provides a universal, algorithm-agnostic format that:

- โœ… Works across **31+ cryptographic algorithms**
- โœ… **Self-describing metadata** enables seamless decryption
- โœ… **Integrity verification** with SHA-256 checksums
- โœ… **Cross-platform compatible** (Rust, Python, JavaScript, Go, etc.)
- โœ… **Future-proof** design allows algorithm migration
- โœ… **Zero dependencies** except serde and sha2

## ๐Ÿš€ Quick Start

### Rust

Add to your `Cargo.toml`:

```toml
[dependencies]
pqc-binary-format = "1.0"
```

### Basic Usage (Rust)

```rust
use pqc_binary_format::{PqcBinaryFormat, Algorithm, PqcMetadata, EncParameters};
use std::collections::HashMap;

// Create metadata with encryption parameters
let metadata = PqcMetadata {
    enc_params: EncParameters {
        iv: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],  // 12-byte nonce
        tag: vec![0; 16],                                  // 16-byte auth tag
        params: HashMap::new(),
    },
    ..Default::default()
};

// Create encrypted data container
let encrypted_data = vec![1, 2, 3, 4, 5];  // Your encrypted bytes
let format = PqcBinaryFormat::new(Algorithm::Hybrid, metadata, encrypted_data);

// Serialize to bytes (for transmission or storage)
let bytes = format.to_bytes().unwrap();

// Deserialize from bytes (includes automatic checksum verification)
let recovered = PqcBinaryFormat::from_bytes(&bytes).unwrap();

assert_eq!(format, recovered);
println!("Algorithm: {}", recovered.algorithm().name());
```

### Python

Install the Python bindings:

```bash
cd bindings/python
pip install maturin
maturin develop --release
```

```python
from pqc_binary_format import Algorithm, EncParameters, PqcMetadata, PqcBinaryFormat

# Create algorithm and metadata
algorithm = Algorithm("hybrid")
enc_params = EncParameters(
    iv=bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
    tag=bytes([0] * 16)
)
metadata = PqcMetadata(enc_params=enc_params, kem_params=None, sig_params=None, compression_params=None)

# Create and serialize format
pqc_format = PqcBinaryFormat(algorithm, metadata, bytes([1, 2, 3, 4, 5]))
serialized = pqc_format.to_bytes()

# Deserialize and verify
deserialized = PqcBinaryFormat.from_bytes(serialized)
deserialized.validate()  # Verify checksum integrity
print(f"Algorithm: {deserialized.algorithm.name}")
```

### JavaScript/TypeScript

Build the WebAssembly bindings:

```bash
cd bindings/javascript
npm install
npm run build
```

```javascript
import init, { WasmAlgorithm, WasmEncParameters, WasmPqcMetadata, WasmPqcBinaryFormat } from './pqc_binary_format.js';

await init();

const algorithm = new WasmAlgorithm('hybrid');
const encParams = new WasmEncParameters(
    new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
    new Uint8Array(16)
);
const metadata = new WasmPqcMetadata(encParams);
const pqcFormat = new WasmPqcBinaryFormat(algorithm, metadata, new Uint8Array([1, 2, 3, 4, 5]));

const serialized = pqcFormat.toBytes();
const deserialized = WasmPqcBinaryFormat.fromBytes(serialized);
console.log(`Algorithm: ${deserialized.algorithm.name}`);
```

### Go

Build the Rust library first, then use the Go bindings:

```bash
cargo build --release
cd bindings/go
go build example.go
```

```go
package main

import (
    "fmt"
    "log"
    pqc "github.com/PQCrypta/pqcrypta-community/bindings/go"
)

func main() {
    iv := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
    tag := make([]byte, 16)
    data := []byte{1, 2, 3, 4, 5}

    format, err := pqc.NewPqcBinaryFormat(pqc.AlgorithmHybrid, iv, tag, data)
    if err != nil {
        log.Fatal(err)
    }
    defer format.Free()

    serialized, _ := format.ToBytes()
    deserialized, _ := pqc.FromBytes(serialized)
    defer deserialized.Free()

    fmt.Printf("Algorithm: %s\n", deserialized.GetAlgorithmName())
}
```

### C/C++

Build the Rust library and generate the C header:

```bash
cargo build --release
cbindgen --config cbindgen.toml --output include/pqc_binary_format.h
cd bindings/c-cpp
make
```

```cpp
#include "pqc_binary_format.h"
#include <iostream>
#include <vector>

int main() {
    std::vector<uint8_t> iv = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    std::vector<uint8_t> tag(16, 0);
    std::vector<uint8_t> data = {1, 2, 3, 4, 5};

    PqcFormatHandle* format = pqc_format_new(
        PQC_ALGORITHM_HYBRID,
        iv.data(), iv.size(),
        tag.data(), tag.size(),
        data.data(), data.size()
    );

    ByteBuffer serialized = pqc_format_to_bytes(format);
    PqcFormatHandle* deserialized = pqc_format_from_bytes(serialized.data, serialized.len);

    char* alg_name = pqc_format_get_algorithm_name(deserialized);
    std::cout << "Algorithm: " << alg_name << std::endl;

    pqc_free_string(alg_name);
    pqc_free_buffer(serialized);
    pqc_format_free(deserialized);
    pqc_format_free(format);

    return 0;
}
```

## ๐ŸŒ Language Bindings

PQC Binary Format provides **production-ready, fully tested bindings** for multiple programming languages. All bindings support the complete API and produce cross-compatible binary formats.

### Available Bindings (v1.0.11)

| Language | Status | Package | Documentation | Examples |
|----------|--------|---------|---------------|----------|
| **Rust** | โœ… Native | `pqc-binary-format` | [docs.rs]https://docs.rs/pqc-binary-format | [3 examples]examples/ |
| **Python** | โœ… Tested | `pqc_binary_format` | [Python README]bindings/python/README.md | [2 examples]examples/python/ |
| **JavaScript/WASM** | โœ… Tested | `pqc_binary_format` (npm) | [JS README]bindings/javascript/README.md | [1 example]examples/javascript/ |
| **Go** | โœ… Tested | `github.com/PQCrypta/pqcrypta-community/bindings/go` | [pkg.go.dev]https://pkg.go.dev/github.com/PQCrypta/pqcrypta-community/bindings/go | [1 example]bindings/go/examples/ |
| **C** | โœ… Tested | FFI via Rust | [C/C++ README]bindings/c-cpp/README.md | [1 example]examples/c/ |
| **C++** | โœ… Tested | FFI via Rust | [C/C++ README]bindings/c-cpp/README.md | [1 example]examples/cpp/ |

### Installation Quick Reference

```bash
# Rust
cargo add pqc-binary-format

# Python (via maturin)
python3 -m venv .venv && source .venv/bin/activate
pip install maturin
maturin develop --release

# JavaScript/WASM (via wasm-pack)
wasm-pack build --target web --features wasm

# Go
go get github.com/PQCrypta/pqcrypta-community/bindings/go

# C/C++ (build from source)
cargo build --release --no-default-features
# Link against target/release/libpqc_binary_format.so
```

### Cross-Language Compatibility

**All language bindings are fully interoperable!** You can:
- โœ… Encrypt data in Python, decrypt in Rust
- โœ… Serialize in Go, deserialize in JavaScript
- โœ… Create format in C++, validate in Python
- โœ… Mix any combination across platforms

Example workflow:
```bash
# Create encrypted data with Python
python3 examples/python/basic_usage.py > data.bin

# Verify with C++
LD_LIBRARY_PATH=target/release ./examples/cpp/basic_usage < data.bin

# Process with Go
cd examples/go && go run basic_usage.go < ../../data.bin
```

### Binding Features

All bindings support:
- โœ… Full algorithm suite (31 algorithms)
- โœ… Metadata serialization/deserialization
- โœ… SHA-256 integrity verification
- โœ… Feature flags (compression, streaming, etc.)
- โœ… Error handling with detailed messages
- โœ… Memory safety (Rust-backed)

### Package Distribution Status

| Platform | Status | Notes |
|----------|--------|-------|
| crates.io (Rust) | โœ… **Published** | **[v1.0.11 live!]https://crates.io/crates/pqc-binary-format** |
| PyPI (Python) | โณ Ready | Maturin build tested, ready for `maturin publish` |
| npm (JavaScript) | โณ Ready | WASM package built with wasm-pack |
| pkg.go.dev (Go) | โณ Ready | Will auto-index on tag push |

## ๐Ÿ“ฆ Binary Format Specification

```text
+-------------------+
| Magic (4 bytes)   | "PQC\x01" - Format identifier
+-------------------+
| Version (1 byte)  | 0x01 - Format version
+-------------------+
| Algorithm (2 bytes)| Algorithm identifier (0x0050 - 0x0506)
+-------------------+
| Flags (1 byte)    | Feature flags (compression, streaming, etc.)
+-------------------+
| Metadata Len (4)  | Length of metadata section
+-------------------+
| Data Len (8)      | Length of encrypted payload
+-------------------+
| Metadata (var)    | Algorithm-specific parameters
+-------------------+
| Data (var)        | Encrypted data
+-------------------+
| Checksum (32)     | SHA-256 integrity checksum
+-------------------+
```

## ๐Ÿ” Supported Algorithms

The format supports 31 cryptographic algorithm identifiers:

### Classical Algorithms
- **Classical** (0x0050): X25519 + Ed25519 + AES-256-GCM
- **Password Classical** (0x0051): Password-based encryption

### Hybrid Algorithms
- **Hybrid** (0x0100): ML-KEM-1024 + X25519 + ML-DSA-87 + Ed25519

### Post-Quantum Algorithms
- **Post-Quantum** (0x0200): ML-KEM-1024 + ML-DSA-87
- **ML-KEM-1024** (0x0202): Pure ML-KEM with AES-256-GCM
- **Multi-KEM** (0x0203): Dual-layer KEM
- **Multi-KEM Triple** (0x0204): Triple-layer KEM
- **Quad-Layer** (0x0205): Four independent layers
- **PQ3-Stack** (0x0207): Forward secrecy stack

### Max Secure Series (0x0300-0x0306)
High-security configurations for enterprise use

### FN-DSA Series (0x0400-0x0407)
Falcon-based signature algorithms

### Experimental (0x0500-0x0506)
Research and next-generation algorithms

### HQC Code-Based Series (0x0600-0x0602)
NIST 2025 Backup KEM standard - code-based cryptography

[View full algorithm list](docs/algorithms.md)

## ๐ŸŽฏ Features

### Feature Flags

Control optional behavior with feature flags:

```rust
use pqc_binary_format::{PqcBinaryFormat, Algorithm, FormatFlags, PqcMetadata, EncParameters};
use std::collections::HashMap;

let flags = FormatFlags::new()
    .with_compression()       // Data was compressed before encryption
    .with_streaming()         // Streaming encryption mode
    .with_additional_auth();  // Additional authentication layer

let metadata = PqcMetadata {
    enc_params: EncParameters {
        iv: vec![1; 12],
        tag: vec![1; 16],
        params: HashMap::new(),
    },
    ..Default::default()
};

let format = PqcBinaryFormat::with_flags(
    Algorithm::QuadLayer,
    flags,
    metadata,
    vec![1, 2, 3],
);

assert!(format.flags().has_compression());
assert!(format.flags().has_streaming());
```

### Metadata Structure

The format includes rich metadata for decryption:

```rust
use pqc_binary_format::{PqcMetadata, KemParameters, SigParameters, EncParameters, CompressionParameters};
use std::collections::HashMap;

let metadata = PqcMetadata {
    // Key Encapsulation (optional)
    kem_params: Some(KemParameters {
        public_key: vec![/* ML-KEM public key */],
        ciphertext: vec![/* encapsulated key */],
        params: HashMap::new(),
    }),

    // Digital Signature (optional)
    sig_params: Some(SigParameters {
        public_key: vec![/* ML-DSA public key */],
        signature: vec![/* signature bytes */],
        params: HashMap::new(),
    }),

    // Symmetric Encryption (required)
    enc_params: EncParameters {
        iv: vec![1; 12],              // Nonce/IV
        tag: vec![1; 16],             // AEAD auth tag
        params: HashMap::new(),
    },

    // Compression (optional)
    compression_params: Some(CompressionParameters {
        algorithm: "zstd".to_string(),
        level: 3,
        original_size: 1024,
        params: HashMap::new(),
    }),

    // Custom parameters (extensible)
    custom: HashMap::new(),
};
```

### Custom Parameters

Add your own metadata:

```rust
use pqc_binary_format::PqcMetadata;

let mut metadata = PqcMetadata::new();
metadata.add_custom("my_param".to_string(), vec![1, 2, 3]);

// Later...
if let Some(value) = metadata.get_custom("my_param") {
    println!("Custom param: {:?}", value);
}
```

## ๐Ÿ” Integrity Verification

Every format includes a SHA-256 checksum calculated over all fields:

```rust
use pqc_binary_format::PqcBinaryFormat;

let bytes = format.to_bytes().unwrap();

// Tamper with the data
// let mut corrupted = bytes.clone();
// corrupted[50] ^= 0xFF;

// Deserialization automatically verifies checksum
match PqcBinaryFormat::from_bytes(&bytes) {
    Ok(format) => println!("โœ“ Checksum valid"),
    Err(e) => println!("โœ— Checksum failed: {}", e),
}
```

## ๐Ÿ“š Examples

### Example 1: Basic Encryption Format

```rust
use pqc_binary_format::{PqcBinaryFormat, Algorithm, PqcMetadata, EncParameters};
use std::collections::HashMap;

fn main() {
    let metadata = PqcMetadata {
        enc_params: EncParameters {
            iv: vec![1; 12],
            tag: vec![1; 16],
            params: HashMap::new(),
        },
        ..Default::default()
    };

    let format = PqcBinaryFormat::new(
        Algorithm::Hybrid,
        metadata,
        vec![/* your encrypted data */],
    );

    // Save to file
    let bytes = format.to_bytes().unwrap();
    std::fs::write("encrypted.pqc", &bytes).unwrap();

    // Load from file
    let loaded_bytes = std::fs::read("encrypted.pqc").unwrap();
    let loaded = PqcBinaryFormat::from_bytes(&loaded_bytes).unwrap();

    println!("Algorithm: {}", loaded.algorithm().name());
}
```

### Example 2: Cross-Language Interoperability

**Rust (Encryption)**
```rust
let format = PqcBinaryFormat::new(Algorithm::PostQuantum, metadata, data);
let bytes = format.to_bytes().unwrap();
// Send bytes to Python/JavaScript/Go/C++
```

**Python (Decryption)**
```python
from pqc_binary_format import PqcBinaryFormat

format = PqcBinaryFormat.from_bytes(bytes)
print(f"Algorithm: {format.algorithm().name()}")
print(f"Data: {len(format.data())} bytes")
```

**JavaScript (Decryption)**
```javascript
const format = WasmPqcBinaryFormat.fromBytes(bytes);
console.log(`Algorithm: ${format.algorithm.name}`);
console.log(`Data: ${format.data.length} bytes`);
```

**Go (Decryption)**
```go
format, _ := pqc.FromBytes(bytes)
defer format.Free()
fmt.Printf("Algorithm: %s\n", format.GetAlgorithmName())
fmt.Printf("Data: %d bytes\n", len(format.GetData()))
```

### Example 3: Algorithm Migration

```rust
// Old data encrypted with Classical algorithm
let old_format = PqcBinaryFormat::from_bytes(&old_encrypted_data)?;
assert_eq!(old_format.algorithm(), Algorithm::Classical);

// Re-encrypt with Post-Quantum algorithm
let plaintext = decrypt_with_classical(&old_format)?;
let new_metadata = create_pq_metadata()?;
let new_format = PqcBinaryFormat::new(
    Algorithm::PostQuantum,
    new_metadata,
    encrypt_with_pq(&plaintext)?,
);

// Same format, different algorithm!
```

## ๐ŸŽ“ Use Cases

### 1. **Cross-Platform Encryption**
Encrypt in Rust, decrypt in Python, JavaScript, or Go using the same format.

### 2. **Long-Term Archival**
Self-describing format ensures data can be decrypted decades later even as algorithms evolve.

### 3. **Algorithm Agility**
Switch between algorithms without changing application code.

### 4. **Compliance & Audit**
Embedded metadata provides audit trail for regulatory compliance (GDPR, HIPAA, etc.).

### 5. **Research & Benchmarking**
Standardized format enables fair comparison of PQC algorithm performance.

## ๐Ÿงช Testing

```bash
# Run tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Run specific test
cargo test test_binary_format_roundtrip
```

## ๐Ÿ“Š Benchmarks

```bash
# Run benchmarks
cargo bench

# View benchmark results
open target/criterion/report/index.html
```

Performance characteristics:
- **Serialization**: ~50 MB/s for typical payloads
- **Deserialization**: ~45 MB/s (includes checksum verification)
- **Overhead**: ~100 bytes + metadata size

## ๐Ÿ”ง Development

### Building from Source

```bash
git clone https://github.com/PQCrypta/pqcrypta-community.git
cd pqcrypta-community
cargo build --release
```

### Running Examples

```bash
cargo run --example basic_usage
cargo run --example with_compression
cargo run --example cross_platform
```

## ๐Ÿค Contributing

We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

### Current Status

- **Language Bindings**: โœ… **Rust** (native), โœ… **Python** (tested v1.0.11), โœ… **JavaScript/WASM** (tested v1.0.11), โœ… **Go** (tested v1.0.11), โœ… **C/C++** (tested v1.0.11)
- **Examples**: โœ… 9 validated examples across 6 languages
- **Package Distribution**: โœ… **crates.io published!** | โณ PyPI, npm, pkg.go.dev ready

### Areas for Contribution

- **Additional Language Bindings**: Java, C#, Ruby, Swift, Kotlin - help us expand!
- **Documentation**: Tutorials, integration guides, video walkthroughs
- **Testing**: Additional test cases, fuzzing, property-based testing
- **Performance**: SIMD optimizations, benchmark improvements
- **Standards**: Help draft RFC for IETF standardization submission
- **Package Publishing**: Help publish to PyPI, npm, and other package registries

## ๐Ÿ“„ License

Licensed under either of:

- MIT License ([LICENSE-MIT]LICENSE-MIT or http://opensource.org/licenses/MIT)
- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)

at your option.

## ๐Ÿ™ Acknowledgments

This format was developed as part of the [PQCrypta](https://pqcrypta.com) enterprise post-quantum cryptography platform. Special thanks to:

- NIST Post-Quantum Cryptography Project
- The Rust cryptography community
- Contributors to pqcrypto, ring, and other foundational crates

## ๐Ÿ“– References

- [NIST Post-Quantum Cryptography]https://csrc.nist.gov/projects/post-quantum-cryptography
- [ML-KEM (Kyber) Specification]https://csrc.nist.gov/pubs/fips/203/final
- [ML-DSA (Dilithium) Specification]https://csrc.nist.gov/pubs/fips/204/final
- [PQCrypta Documentation]https://pqcrypta.com/docs

## ๐Ÿ”— Related Projects

- [pqcrypto]https://github.com/rustpq/pqcrypto - Rust PQC implementations
- [Open Quantum Safe]https://openquantumsafe.org/ - PQC library collection
- [CIRCL]https://github.com/cloudflare/circl - Cloudflare's crypto library

## ๐Ÿ’ฌ Community & Support

- **GitHub Issues**: [Report bugs]https://github.com/PQCrypta/pqcrypta-community/issues
- **Discussions**: [Ask questions]https://github.com/PQCrypta/pqcrypta-community/discussions
- **Website**: [pqcrypta.com]https://pqcrypta.com
- **Documentation**: [docs.rs/pqc-binary-format]https://docs.rs/pqc-binary-format

---

**Made with โค๏ธ by the PQCrypta Community**

*Securing the future, one byte at a time.*