Botan  2.1.0
Crypto and TLS for C++11
hmac.cpp
Go to the documentation of this file.
1 /*
2 * HMAC
3 * (C) 1999-2007,2014 Jack Lloyd
4 * 2007 Yves Jerschow
5 *
6 * Botan is released under the Simplified BSD License (see license.txt)
7 */
8 
9 #include <botan/hmac.h>
10 
11 namespace Botan {
12 
13 /*
14 * Update a HMAC Calculation
15 */
16 void HMAC::add_data(const uint8_t input[], size_t length)
17  {
18  m_hash->update(input, length);
19  }
20 
21 /*
22 * Finalize a HMAC Calculation
23 */
24 void HMAC::final_result(uint8_t mac[])
25  {
26  m_hash->final(mac);
27  m_hash->update(m_okey);
28  m_hash->update(mac, output_length());
29  m_hash->final(mac);
30  m_hash->update(m_ikey);
31  }
32 
33 /*
34 * HMAC Key Schedule
35 */
36 void HMAC::key_schedule(const uint8_t key[], size_t length)
37  {
38  m_hash->clear();
39 
40  m_ikey.resize(m_hash->hash_block_size());
41  m_okey.resize(m_hash->hash_block_size());
42 
43  std::fill(m_ikey.begin(), m_ikey.end(), 0x36);
44  std::fill(m_okey.begin(), m_okey.end(), 0x5C);
45 
46  if(length > m_hash->hash_block_size())
47  {
48  secure_vector<uint8_t> hmac_key = m_hash->process(key, length);
49  xor_buf(m_ikey, hmac_key, hmac_key.size());
50  xor_buf(m_okey, hmac_key, hmac_key.size());
51  }
52  else
53  {
54  xor_buf(m_ikey, key, length);
55  xor_buf(m_okey, key, length);
56  }
57 
58  m_hash->update(m_ikey);
59  }
60 
61 /*
62 * Clear memory of sensitive data
63 */
65  {
66  m_hash->clear();
67  zap(m_ikey);
68  zap(m_okey);
69  }
70 
71 /*
72 * Return the name of this type
73 */
74 std::string HMAC::name() const
75  {
76  return "HMAC(" + m_hash->name() + ")";
77  }
78 
79 /*
80 * Return a clone of this object
81 */
83  {
84  return new HMAC(m_hash->clone());
85  }
86 
87 /*
88 * HMAC Constructor
89 */
91  {
92  if(m_hash->hash_block_size() == 0)
93  throw Invalid_Argument("HMAC cannot be used with " + m_hash->name());
94  }
95 
96 }
void xor_buf(T out[], const T in[], size_t length)
Definition: mem_ops.h:115
MessageAuthenticationCode * clone() const override
Definition: hmac.cpp:82
void zap(std::vector< T, Alloc > &vec)
Definition: secmem.h:221
size_t output_length() const override
Definition: hmac.h:26
Definition: alg_id.cpp:13
void clear() override
Definition: hmac.cpp:64
HMAC(HashFunction *hash)
Definition: hmac.cpp:90
std::string name() const override
Definition: hmac.cpp:74
std::unique_ptr< HashFunction > m_hash
Definition: tpm.cpp:439
MechanismType hash