Coverage Report

Created: 2024-06-28 06:08

/src/botan/src/lib/pubkey/rfc6979/rfc6979.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* RFC 6979 Deterministic Nonce Generator
3
* (C) 2014,2015 Jack Lloyd
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7
8
#include <botan/internal/rfc6979.h>
9
10
#include <botan/hmac_drbg.h>
11
#include <botan/mac.h>
12
#include <botan/internal/fmt.h>
13
14
namespace Botan {
15
16
RFC6979_Nonce_Generator::RFC6979_Nonce_Generator(std::string_view hash, const BigInt& order, const BigInt& x) :
17
      m_order(order),
18
      m_qlen(m_order.bits()),
19
      m_rlen(m_qlen / 8 + (m_qlen % 8 ? 1 : 0)),
20
      m_rng_in(m_rlen * 2),
21
214
      m_rng_out(m_rlen) {
22
214
   m_hmac_drbg = std::make_unique<HMAC_DRBG>(MessageAuthenticationCode::create_or_throw(fmt("HMAC({})", hash)));
23
24
214
   x.serialize_to(std::span{m_rng_in}.first(m_rlen));
25
214
}
26
27
214
RFC6979_Nonce_Generator::~RFC6979_Nonce_Generator() = default;
28
29
200
const BigInt& RFC6979_Nonce_Generator::nonce_for(const BigInt& m) {
30
200
   m.serialize_to(std::span{m_rng_in}.subspan(m_rlen));
31
200
   m_hmac_drbg->clear();
32
200
   m_hmac_drbg->initialize_with(m_rng_in.data(), m_rng_in.size());
33
34
343
   do {
35
343
      m_hmac_drbg->randomize(m_rng_out.data(), m_rng_out.size());
36
343
      m_k._assign_from_bytes(m_rng_out);
37
343
      m_k >>= (8 * m_rlen - m_qlen);
38
343
   } while(m_k == 0 || m_k >= m_order);
39
40
200
   return m_k;
41
200
}
42
43
0
BigInt generate_rfc6979_nonce(const BigInt& x, const BigInt& q, const BigInt& h, std::string_view hash) {
44
0
   RFC6979_Nonce_Generator gen(hash, q, x);
45
0
   BigInt k = gen.nonce_for(h);
46
0
   return k;
47
0
}
48
49
}  // namespace Botan