SH2SC-EDT
Self-Healing Hardware and Software Complex for Encrypted Data Transmission
Loading...
Searching...
No Matches
csprng.h
Go to the documentation of this file.
1
39#pragma once
40
41#include <Arduino.h>
42#include <ChaCha.h>
43
49static const uint8_t CSPRNG_BLOCK_BYTES = 64u;
50
52static ChaCha s_chacha;
53
56
63
75static void s_fillKeystreamBlock() {
76 // Zero the cache so the in-place XOR yields the raw keystream.
78
79 // XOR the all-zero input with ChaCha20's keystream -> raw keystream output.
80 // The library advances its internal block counter after every 64-byte call.
82
83 s_keystreamUsed = 0u;
84}
85
102void initCSPRNG(const uint8_t* hardwareSeed) {
103 // Install the 256-bit hardware-entropy key into the ChaCha20 engine.
104 s_chacha.setKey(hardwareSeed, 32u);
105
106 // Set a zero IV (nonce). Safe because the key is unique per session.
107 // The IV is 8 bytes for djb-ChaCha (not the 12-byte IETF variant used for packets).
108 static const uint8_t zeroIV[8] = {};
109 s_chacha.setIV(zeroIV, sizeof(zeroIV));
110
111 // Pre-compute the first keystream block so the first caller incurs no stall.
113}
114
127 // Transparently refill the cache when fewer than 4 bytes remain.
130 }
131
132 // Assemble four consecutive keystream bytes as a little-endian uint32_t.
133 const uint32_t value =
134 static_cast<uint32_t>(s_keystreamBuf[s_keystreamUsed]) |
135 (static_cast<uint32_t>(s_keystreamBuf[s_keystreamUsed + 1u]) << 8u) |
136 (static_cast<uint32_t>(s_keystreamBuf[s_keystreamUsed + 2u]) << 16u) |
137 (static_cast<uint32_t>(s_keystreamBuf[s_keystreamUsed + 3u]) << 24u);
138
139 s_keystreamUsed += 4u;
140 return value;
141}
static ChaCha s_chacha
ChaCha20 cipher object (20-round configuration by default constructor).
Definition csprng.h:52
uint32_t getSecureRandom32()
Return 32 bits of CSPRNG output (non-blocking).
Definition csprng.h:126
static uint8_t s_keystreamUsed
Number of bytes consumed from s_keystreamBuf so far.
Definition csprng.h:62
static const uint8_t CSPRNG_BLOCK_BYTES
Size of one ChaCha20 keystream output block in bytes.
Definition csprng.h:49
static uint8_t s_keystreamBuf[CSPRNG_BLOCK_BYTES]
One-block keystream cache. Refilled automatically when s_keystreamUsed >= CSPRNG_BLOCK_BYTES.
Definition csprng.h:55
static void s_fillKeystreamBlock()
Produce the next 64-byte ChaCha20 keystream block into s_keystreamBuf.
Definition csprng.h:75
void initCSPRNG(const uint8_t *hardwareSeed)
Seed the ChaCha20 CSPRNG with 256 bits of hardware entropy.
Definition csprng.h:102