aboutsummaryrefslogtreecommitdiffstats
path: root/src/kdf/tls_prf/prf_tls.cpp
blob: 7345f11c565b5ac4d1d3dc2d76dd6bb1f1231b7e (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
* TLS v1.0 and v1.2 PRFs
* (C) 2004-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/prf_tls.h>
#include <botan/internal/xor_buf.h>
#include <botan/hmac.h>
#include <botan/md5.h>
#include <botan/sha160.h>

namespace Botan {

namespace {

/*
* TLS PRF P_hash function
*/
void P_hash(byte output[], u32bit output_len,
            MessageAuthenticationCode* mac,
            const byte secret[], u32bit secret_len,
            const byte seed[], u32bit seed_len)
   {
   mac->set_key(secret, secret_len);

   SecureVector<byte> A(seed, seed_len);

   while(output_len)
      {
      const u32bit this_block_len =
         std::min(mac->OUTPUT_LENGTH, output_len);

      A = mac->process(A);

      mac->update(A);
      mac->update(seed, seed_len);
      SecureVector<byte> block = mac->final();

      xor_buf(output, &block[0], this_block_len);
      output_len -= this_block_len;
      output += this_block_len;
      }
   }

}

/*
* TLS PRF Constructor and Destructor
*/
TLS_PRF::TLS_PRF()
   {
   hmac_md5 = new HMAC(new MD5);
   hmac_sha1 = new HMAC(new SHA_160);
   }

TLS_PRF::~TLS_PRF()
   {
   delete hmac_md5;
   delete hmac_sha1;
   }

/*
* TLS PRF
*/
SecureVector<byte> TLS_PRF::derive(u32bit key_len,
                                   const byte secret[], u32bit secret_len,
                                   const byte seed[], u32bit seed_len) const
   {
   SecureVector<byte> output(key_len);

   u32bit S1_len = (secret_len + 1) / 2,
          S2_len = (secret_len + 1) / 2;
   const byte* S1 = secret;
   const byte* S2 = secret + (secret_len - S2_len);

   P_hash(output, key_len, hmac_md5,  S1, S1_len, seed, seed_len);
   P_hash(output, key_len, hmac_sha1, S2, S2_len, seed, seed_len);

   return output;
   }

/*
* TLS v1.2 PRF Constructor and Destructor
*/
TLS_12_PRF::TLS_12_PRF(HashFunction* hash)
   {
   hmac = new HMAC(hash);
   }

TLS_12_PRF::~TLS_12_PRF()
   {
   delete hmac;
   }

SecureVector<byte> TLS_12_PRF::derive(u32bit key_len,
                                      const byte secret[], u32bit secret_len,
                                      const byte seed[], u32bit seed_len) const
   {
   SecureVector<byte> output(key_len);

   P_hash(output, key_len, hmac, secret, secret_len, seed, seed_len);

   return output;
   }

}