Botan 3.5.0
Crypto and TLS for C&
chacha_rng.cpp
Go to the documentation of this file.
1/*
2* ChaCha_RNG
3* (C) 2017 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/chacha_rng.h>
9
10namespace Botan {
11
13 m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
14 m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
15 clear();
16}
17
18ChaCha_RNG::ChaCha_RNG(std::span<const uint8_t> seed) : Stateful_RNG() {
19 m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
20 m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
21 clear();
22 add_entropy(seed);
23}
24
25ChaCha_RNG::ChaCha_RNG(RandomNumberGenerator& underlying_rng, size_t reseed_interval) :
26 Stateful_RNG(underlying_rng, reseed_interval) {
27 m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
28 m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
29 clear();
30}
31
33 Entropy_Sources& entropy_sources,
34 size_t reseed_interval) :
35 Stateful_RNG(underlying_rng, entropy_sources, reseed_interval) {
36 m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
37 m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
38 clear();
39}
40
41ChaCha_RNG::ChaCha_RNG(Entropy_Sources& entropy_sources, size_t reseed_interval) :
42 Stateful_RNG(entropy_sources, reseed_interval) {
43 m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
44 m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
45 clear();
46}
47
48void ChaCha_RNG::clear_state() {
49 m_hmac->set_key(std::vector<uint8_t>(m_hmac->output_length(), 0x00));
50 m_chacha->set_key(m_hmac->final());
51}
52
53void ChaCha_RNG::generate_output(std::span<uint8_t> output, std::span<const uint8_t> input) {
54 BOTAN_ASSERT_NOMSG(!output.empty());
55
56 if(!input.empty()) {
57 update(input);
58 }
59
60 m_chacha->write_keystream(output);
61}
62
63void ChaCha_RNG::update(std::span<const uint8_t> input) {
64 m_hmac->update(input);
65 m_chacha->set_key(m_hmac->final());
66 const auto mac_key = m_chacha->keystream_bytes(m_hmac->output_length());
67 m_hmac->set_key(mac_key);
68}
69
71 return 256;
72}
73
74} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
size_t security_level() const override
static std::unique_ptr< MessageAuthenticationCode > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition mac.cpp:148
void add_entropy(std::span< const uint8_t > input)
Definition rng.h:75
static std::unique_ptr< StreamCipher > create_or_throw(std::string_view algo_spec, std::string_view provider="")
int(* update)(CTX *, const void *, CC_LONG len)