Files
zigp2p/docs/CRYPTO_QUICKREF.md
2026-02-06 21:03:59 -03:00

5.8 KiB

Crypto Module Quick Reference

TL;DR

The encryption module you requested already exists at src/protocol/crypto.zig (948 lines) with full integration in src/protocol/serializer.zig.

File Locations

src/protocol/
├── crypto.zig           # Core crypto (948 lines) - YOUR REQUESTED MODULE
├── encryption.zig       # Advanced nonce management (520+ lines)
├── serializer.zig       # Integration (lines 254-343, 450-547)
└── protocol.zig         # ENCRYPTED flag definition

Basic Usage

1. Initialize CryptoManager

const crypto = @import("src/protocol/crypto.zig");

var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();

2. Register Peer Key

const peer_id = [_]u8{0x42} ** 32;
const encryption_key = [_]u8{0xAB} ** 32;
const hmac_key = [_]u8{0xCD} ** 32;

try crypto_mgr.setKeyForPeer(peer_id, encryption_key);
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);

3. Encrypt/Decrypt

// Encrypt
const plaintext = "Secret message";
const ciphertext = try crypto_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);

// Decrypt
const decrypted = try crypto_mgr.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);

4. Message Serialization (Integrated)

const serializer = @import("src/protocol/serializer.zig");

var ser = serializer.MessageSerializer.initWithCrypto(
    allocator,
    &crypto_mgr,
    peer_id
);

// Serialize with encryption (automatic)
const msg = message.Message{ .ping = message.Ping.init(123) };
var buffer: [1024]u8 = undefined;
const size = try ser.serializeEncrypted(msg, &buffer);

// Deserialize with decryption (automatic)
var decrypted_msg = try ser.deserializeDecrypted(buffer[0..size]);
defer decrypted_msg.deinit();

Key Functions

CryptoManager (src/protocol/crypto.zig)

Function Purpose Line
init(allocator) Create manager 299
deinit() Cleanup (secure zero) 324
setKeyForPeer(peer_id, key) Register encryption key 391
setHmacKeyForPeer(peer_id, key) Register HMAC key 400
encrypt(peer_id, plaintext) Encrypt data 764
decrypt(peer_id, ciphertext) Decrypt data 818
initiateKeyExchange(peer_id) Start DH exchange 454
respondToKeyExchange(...) Respond to exchange 496
completeKeyExchange(...) Finish exchange 618

MessageSerializer (src/protocol/serializer.zig)

Function Purpose Line
initWithCrypto(alloc, crypto, peer) Create with encryption 131
serializeEncrypted(msg, buffer) Serialize + encrypt 254
deserializeDecrypted(buffer) Decrypt + deserialize 450
serialize(msg, buffer) Serialize + HMAC (no encrypt) 172
deserialize(buffer) Deserialize + verify HMAC 346

Message Format

Without Encryption

[Header (91 bytes)] [Payload (variable)] [HMAC (32 bytes)]

With Encryption

[Header (91 bytes)] [Nonce(12) + Ciphertext + Tag(16)] [HMAC (32 bytes)]
                     └─────────── Encrypted Payload ──────────┘

Security Features

✅ Encryption: ChaCha20-Poly1305 AEAD (256-bit keys) ✅ Authentication: Poly1305 (16-byte tags) + HMAC-SHA256 (32-byte tags) ✅ Key Exchange: X25519 DH + Ed25519 signatures ✅ Nonce Safety: Counter-based, generation tracking, exhaustion detection ✅ Key Rotation: Automatic (age/usage/exhaustion triggered) ✅ Memory Security: Secure zeroing on cleanup ✅ Rate Limiting: Anti-DoS (5s interval, 12/hour max)

Tests

Run existing tests:

zig build test              # All tests (has unrelated build error in handler.zig)
zig test src/protocol/crypto.zig        # Crypto tests only
zig test src/protocol/encryption.zig    # Encryption manager tests
zig test src/protocol/serializer.zig    # Serializer tests (includes crypto integration)

Error Handling

pub const CryptoError = error{
    NoKeyForPeer,              // No encryption key registered
    InvalidCiphertext,          // Malformed ciphertext
    DecryptionFailed,          // Authentication failed or wrong key
    OutOfMemory,               // Allocation failed
    NoHmacKeyForPeer,         // No HMAC key registered
    SignatureVerificationFailed, // Invalid Ed25519 signature
    WeakPublicKey,             // Low-order DH point detected
    NonceExhaustion,           // Nonce counter exhausted (need rotation)
    KeyExchangeInProgress,     // Exchange already in progress
};

Important Notes

  1. Mandatory Encryption: REQUIRE_ENCRYPTION = true (compile-time enforced)
  2. Mandatory Authentication: REQUIRE_AUTHENTICATION = true (compile-time enforced)
  3. Key Exchange Messages: NOT encrypted (required for establishing encryption)
  4. Memory Management: All encrypt/decrypt functions return allocated memory - caller must free
  5. Nonce Uniqueness: EncryptionManager provides counter-based nonces (no collision risk)
  6. TOFU Security: First key from peer is accepted (configurable callback)

Quick Start Checklist

  • Module exists at src/protocol/crypto.zig ✅
  • CryptoManager implemented ✅
  • ChaCha20-Poly1305 encryption ✅
  • Serializer integration ✅
  • ENCRYPTED flag handling ✅
  • Tests written and passing ✅
  • HMAC authentication ✅ (bonus)
  • Key exchange protocol ✅ (bonus)
  • Nonce management ✅ (bonus)
  • Key rotation ✅ (bonus)

Documentation

  • Full documentation: CRYPTO_IMPLEMENTATION.md
  • Status report: CRYPTO_STATUS.md
  • This quick ref: CRYPTO_QUICKREF.md

Support

For questions about the crypto module:

  1. Read inline documentation in src/protocol/crypto.zig
  2. Check tests for usage examples
  3. Review security notes in file headers