Botan  1.10.9
hmac.cpp
Go to the documentation of this file.
1 /*
2 * HMAC
3 * (C) 1999-2007 Jack Lloyd
4 * 2007 Yves Jerschow
5 *
6 * Distributed under the terms of the Botan license
7 */
8 
9 #include <botan/hmac.h>
10 #include <botan/internal/xor_buf.h>
11 
12 namespace Botan {
13 
14 /*
15 * Update a HMAC Calculation
16 */
17 void HMAC::add_data(const byte input[], size_t length)
18  {
19  hash->update(input, length);
20  }
21 
22 /*
23 * Finalize a HMAC Calculation
24 */
25 void HMAC::final_result(byte mac[])
26  {
27  hash->final(mac);
28  hash->update(o_key);
29  hash->update(mac, output_length());
30  hash->final(mac);
31  hash->update(i_key);
32  }
33 
34 /*
35 * HMAC Key Schedule
36 */
37 void HMAC::key_schedule(const byte key[], size_t length)
38  {
39  hash->clear();
40  std::fill(i_key.begin(), i_key.end(), 0x36);
41  std::fill(o_key.begin(), o_key.end(), 0x5C);
42 
43  if(length > hash->hash_block_size())
44  {
45  SecureVector<byte> hmac_key = hash->process(key, length);
46  xor_buf(i_key, hmac_key, hmac_key.size());
47  xor_buf(o_key, hmac_key, hmac_key.size());
48  }
49  else
50  {
51  xor_buf(i_key, key, length);
52  xor_buf(o_key, key, length);
53  }
54 
55  hash->update(i_key);
56  }
57 
58 /*
59 * Clear memory of sensitive data
60 */
62  {
63  hash->clear();
64  zeroise(i_key);
65  zeroise(o_key);
66  }
67 
68 /*
69 * Return the name of this type
70 */
71 std::string HMAC::name() const
72  {
73  return "HMAC(" + hash->name() + ")";
74  }
75 
76 /*
77 * Return a clone of this object
78 */
80  {
81  return new HMAC(hash->clone());
82  }
83 
84 /*
85 * HMAC Constructor
86 */
87 HMAC::HMAC(HashFunction* hash_in) : hash(hash_in)
88  {
89  if(hash->hash_block_size() == 0)
90  throw Invalid_Argument("HMAC cannot be used with " + hash->name());
91 
92  i_key.resize(hash->hash_block_size());
93  o_key.resize(hash->hash_block_size());
94  }
95 
96 }
void resize(size_t n)
Definition: secmem.h:211
virtual void clear()=0
std::string name() const
Definition: hmac.cpp:71
std::invalid_argument Invalid_Argument
Definition: exceptn.h:20
virtual HashFunction * clone() const =0
void clear()
Definition: hmac.cpp:61
unsigned char byte
Definition: types.h:22
MessageAuthenticationCode * mac
Definition: fpe_fe1.cpp:94
void update(const byte in[], size_t length)
Definition: buf_comp.h:33
SecureVector< byte > process(const byte in[], size_t length)
Definition: buf_comp.h:101
virtual std::string name() const =0
void final(byte out[])
Definition: buf_comp.h:80
virtual size_t hash_block_size() const
Definition: hash.h:32
HMAC(HashFunction *hash)
Definition: hmac.cpp:87
MessageAuthenticationCode * clone() const
Definition: hmac.cpp:79
void xor_buf(byte out[], const byte in[], size_t length)
Definition: xor_buf.h:21
void zeroise(MemoryRegion< T > &vec)
Definition: secmem.h:415
size_t output_length() const
Definition: hmac.h:26