aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/pubkey/rfc6979/rfc6979.cpp
blob: 21d6c356ad0a663d0387b9060b4b794d61ebe624 (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
/*
* RFC 6979 Deterministic Nonce Generator
* (C) 2014 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/rfc6979.h>
#include <botan/hmac_drbg.h>
#include <botan/libstate.h>
#include <botan/scan_name.h>

namespace Botan {

std::string hash_for_deterministic_signature(const std::string& emsa)
   {
   SCAN_Name emsa_name(emsa);

   if(emsa_name.arg_count() > 0)
      {
      const std::string pos_hash = emsa_name.arg(0);
      if(global_state().algorithm_factory().prototype_hash_function(pos_hash))
         return pos_hash;
      }

   return "SHA-512"; // safe default if nothing we understand
   }

BigInt generate_rfc6979_nonce(const BigInt& x,
                              const BigInt& q,
                              const BigInt& h,
                              const std::string& hash)
   {
   Algorithm_Factory& af = global_state().algorithm_factory();

   HMAC_DRBG rng(af.make_mac("HMAC(" + hash + ")"), nullptr);

   const size_t qlen = q.bits();
   const size_t rlen = qlen / 8 + (qlen % 8 ? 1 : 0);

   secure_vector<byte> input = BigInt::encode_1363(x, rlen);

   input += BigInt::encode_1363(h, rlen);

   rng.add_entropy(&input[0], input.size());

   BigInt k;

   secure_vector<byte> kbits(rlen);

   while(k == 0 || k >= q)
      {
      rng.randomize(&kbits[0], kbits.size());
      k = BigInt::decode(kbits) >> (8*rlen - qlen);
      }

   return k;
   }

}