summaryrefslogtreecommitdiffstats
path: root/comm/third_party/botan/src/lib/rng/chacha_rng/chacha_rng.cpp
blob: 3dc69ec1b8a4731cc31ce29d74840f1562ce7c9d (plain)
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
/*
* ChaCha_RNG
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/chacha_rng.h>

namespace Botan {

ChaCha_RNG::ChaCha_RNG() : Stateful_RNG()
   {
   m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
   m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
   clear();
   }

ChaCha_RNG::ChaCha_RNG(const secure_vector<uint8_t>& seed) : Stateful_RNG()
   {
   m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
   m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
   clear();
   add_entropy(seed.data(), seed.size());
   }

ChaCha_RNG::ChaCha_RNG(RandomNumberGenerator& underlying_rng,
                       size_t reseed_interval) :
   Stateful_RNG(underlying_rng, reseed_interval)
   {
   m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
   m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
   clear();
   }

ChaCha_RNG::ChaCha_RNG(RandomNumberGenerator& underlying_rng,
                       Entropy_Sources& entropy_sources,
                       size_t reseed_interval) :
   Stateful_RNG(underlying_rng, entropy_sources, reseed_interval)
   {
   m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
   m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
   clear();
   }

ChaCha_RNG::ChaCha_RNG(Entropy_Sources& entropy_sources,
                       size_t reseed_interval) :
   Stateful_RNG(entropy_sources, reseed_interval)
   {
   m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)");
   m_chacha = StreamCipher::create_or_throw("ChaCha(20)");
   clear();
   }

void ChaCha_RNG::clear_state()
   {
   m_hmac->set_key(std::vector<uint8_t>(m_hmac->output_length(), 0x00));
   m_chacha->set_key(m_hmac->final());
   }

void ChaCha_RNG::generate_output(uint8_t output[], size_t output_len,
                                 const uint8_t input[], size_t input_len)
   {
   if(input_len > 0)
      {
      update(input, input_len);
      }

   m_chacha->write_keystream(output, output_len);
   }

void ChaCha_RNG::update(const uint8_t input[], size_t input_len)
   {
   m_hmac->update(input, input_len);
   m_chacha->set_key(m_hmac->final());

   secure_vector<uint8_t> mac_key(m_hmac->output_length());
   m_chacha->write_keystream(mac_key.data(), mac_key.size());
   m_hmac->set_key(mac_key);
   }

size_t ChaCha_RNG::security_level() const
   {
   return 256;
   }

}