Raw ↗
+ +
2da5fe7 OpenAVX v0.2.0 - High-performance open-standard IP audio and video transport suite
saifmukhtar · 2026-11-24
1 /*
2 * SPDX-License-Identifier: AGPL-3.0-or-later WITH Classpath-exception-2.0
3 * Copyright (c) 2026 Saif Mukhtar
4 *
5 * OpenAVX - Open Audio-Video eXchange
6 * include/avx_crypto.h - Native End-to-End Encryption (ChaCha20-Poly1305 / XChaCha20)
7 */
8  
9 #ifndef AVX_CRYPTO_H
10 #define AVX_CRYPTO_H
11  
12 #include <stdint.h>
13 #include <stdbool.h>
14 #include <stddef.h>
15 #include "avx_platform.h"
16 #include "openavx.h"
17  
18 #define AVX_CRYPTO_KEY_SIZE 32 /* 256-bit symmetric master key */
19 #define AVX_CRYPTO_MAC_SIZE 16 /* 128-bit Poly1305 authentication tag */
20 #define AVX_CRYPTO_NONCE_SIZE 24 /* 192-bit XChaCha20 nonce */
21 #define AVX_CRYPTO_SALT_SIZE 8 /* 64-bit session salt */
22 #define AVX_CRYPTO_OVERHEAD (AVX_CRYPTO_SALT_SIZE + AVX_CRYPTO_MAC_SIZE) /* 24 bytes */
23  
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27  
28 typedef struct {
29 uint8_t key[AVX_CRYPTO_KEY_SIZE];
30 uint8_t session_salt[AVX_CRYPTO_SALT_SIZE];
31 bool enabled;
32 } avx_crypto_ctx_t;
33  
34 /**
35 * Initializes a crypto context from a user-supplied passphrase and stream name.
36 * Uses BLAKE2b to derive a cryptographically strong 256-bit master key.
37 * If passphrase is NULL or empty string, context is disabled (enabled = false).
38 */
39 OPENAVX_API int avx_crypto_init(avx_crypto_ctx_t *ctx, const char *passphrase, const char *stream_name);
40  
41 /**
42 * Generates a fresh random 8-byte session salt for sender session.
43 */
44 OPENAVX_API void avx_crypto_generate_salt(avx_crypto_ctx_t *ctx);
45  
46 /**
47 * Wipes sensitive key material from memory.
48 */
49 OPENAVX_API void avx_crypto_wipe(avx_crypto_ctx_t *ctx);
50  
51 /**
52 * Encrypts and authenticates a fragment payload using XChaCha20-Poly1305.
53 * The 32-byte UDP header is authenticated as Additional Data (AD).
54 *
55 * out_buf layout: [session_salt: 8 bytes] [cipher_payload: plain_len bytes] [mac: 16 bytes]
56 * out_len will be plain_len + AVX_CRYPTO_OVERHEAD (plain_len + 24).
57 */
58 OPENAVX_API int avx_crypto_encrypt_payload(const avx_crypto_ctx_t *ctx,
59 uint32_t frame_seq, uint16_t frag_idx, uint16_t frag_count,
60 const void *header_ad, size_t ad_len,
61 const void *plain_payload, size_t plain_len,
62 void *out_buf, size_t *out_len);
63  
64 /**
65 * Decrypts and verifies a fragment payload using XChaCha20-Poly1305.
66 * in_buf layout: [session_salt: 8 bytes] [cipher_payload: (in_len - 24) bytes] [mac: 16 bytes]
67 *
68 * Returns 0 on success, -1 on MAC failure / tampering.
69 */
70 OPENAVX_API int avx_crypto_decrypt_payload(const avx_crypto_ctx_t *ctx,
71 uint32_t frame_seq, uint16_t frag_idx, uint16_t frag_count,
72 const void *header_ad, size_t ad_len,
73 const void *in_buf, size_t in_len,
74 void *plain_out, size_t *out_plain_len);
75  
76 #ifdef __cplusplus
77 }
78 #endif
79  
80 #endif /* AVX_CRYPTO_H */