/ src / crypto / hmac_sha256.cpp
hmac_sha256.cpp
 1  // Copyright (c) 2014-present The Bitcoin Core 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/hmac_sha256.h>
 6  
 7  #include <crypto/sha256.h>
 8  
 9  #include <cstring>
10  
11  CHMAC_SHA256::CHMAC_SHA256(const unsigned char* key, size_t keylen)
12  {
13      unsigned char rkey[64];
14      if (keylen <= 64) {
15          memcpy(rkey, key, keylen);
16          memset(rkey + keylen, 0, 64 - keylen);
17      } else {
18          CSHA256().Write(key, keylen).Finalize(rkey);
19          memset(rkey + 32, 0, 32);
20      }
21  
22      for (int n = 0; n < 64; n++)
23          rkey[n] ^= 0x5c;
24      outer.Write(rkey, 64);
25  
26      for (int n = 0; n < 64; n++)
27          rkey[n] ^= 0x5c ^ 0x36;
28      inner.Write(rkey, 64);
29  }
30  
31  void CHMAC_SHA256::Finalize(unsigned char hash[OUTPUT_SIZE])
32  {
33      unsigned char temp[32];
34      inner.Finalize(temp);
35      outer.Write(temp, 32).Finalize(hash);
36  }