Line data Source code
1 : // Copyright (c) 2014 The Bitcoin developers
2 : // Distributed under the MIT software license, see the accompanying
3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 :
5 : #include "crypto/rfc6979_hmac_sha256.h"
6 :
7 : #include <string.h>
8 :
9 : #include <algorithm>
10 :
11 : static const unsigned char zero[1] = {0x00};
12 : static const unsigned char one[1] = {0x01};
13 :
14 2 : RFC6979_HMAC_SHA256::RFC6979_HMAC_SHA256(const unsigned char* key, size_t keylen, const unsigned char* msg, size_t msglen) : retry(false)
15 : {
16 2 : memset(V, 0x01, sizeof(V));
17 2 : memset(K, 0x00, sizeof(K));
18 :
19 2 : CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Write(zero, sizeof(zero)).Write(key, keylen).Write(msg, msglen).Finalize(K);
20 2 : CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Finalize(V);
21 2 : CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Write(one, sizeof(one)).Write(key, keylen).Write(msg, msglen).Finalize(K);
22 2 : CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Finalize(V);
23 2 : }
24 :
25 2 : RFC6979_HMAC_SHA256::~RFC6979_HMAC_SHA256()
26 : {
27 2 : memset(V, 0x01, sizeof(V));
28 2 : memset(K, 0x00, sizeof(K));
29 2 : }
30 :
31 6 : void RFC6979_HMAC_SHA256::Generate(unsigned char* output, size_t outputlen)
32 : {
33 6 : if (retry) {
34 4 : CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Write(zero, sizeof(zero)).Finalize(K);
35 4 : CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Finalize(V);
36 : }
37 :
38 12 : while (outputlen > 0) {
39 6 : CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Finalize(V);
40 6 : size_t len = std::min(outputlen, sizeof(V));
41 6 : memcpy(output, V, len);
42 6 : output += len;
43 6 : outputlen -= len;
44 : }
45 :
46 6 : retry = true;
47 6 : }
|