aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/kdf/hkdf/hkdf.cpp
blob: 8c92c779be0a5a6c6e8cde8b392c6d9055fdb404 (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
/*
* HKDF
* (C) 2013,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/kdf_utils.h>
#include <botan/hkdf.h>

namespace Botan {

BOTAN_REGISTER_NAMED_T(KDF, "HKDF", HKDF, HKDF::make);

HKDF* HKDF::make(const Spec& spec)
   {
   if(auto mac = make_a<MessageAuthenticationCode>(spec.arg(0)))
      return new HKDF(mac);

   if(auto mac = make_a<MessageAuthenticationCode>("HMAC(" + spec.arg(0) + ")"))
      return new HKDF(mac);

   return nullptr;
   }

size_t HKDF::kdf(byte out[], size_t out_len,
                 const byte secret[], size_t secret_len,
                 const byte salt[], size_t salt_len) const
   {
   m_prf->set_key(secret, secret_len);

   byte counter = 1;
   secure_vector<byte> h;
   size_t offset = 0;

   while(offset != out_len && counter != 0)
      {
      m_prf->update(h);
      m_prf->update(salt, salt_len);
      m_prf->update(counter++);
      m_prf->final(h);

      const size_t written = std::min(h.size(), out_len - offset);
      copy_mem(&out[offset], &h[0], written);
      offset += written;
      }

   return offset;
   }

}