Coverage Report

Created: 2020-10-17 06:46

/src/botan/src/lib/kdf/prf_x942/prf_x942.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* X9.42 PRF
3
* (C) 1999-2007 Jack Lloyd
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7
8
#include <botan/prf_x942.h>
9
#include <botan/der_enc.h>
10
#include <botan/hash.h>
11
#include <botan/loadstor.h>
12
#include <algorithm>
13
14
namespace Botan {
15
16
namespace {
17
18
/*
19
* Encode an integer as an OCTET STRING
20
*/
21
std::vector<uint8_t> encode_x942_int(uint32_t n)
22
0
   {
23
0
   uint8_t n_buf[4] = { 0 };
24
0
   store_be(n, n_buf);
25
0
26
0
   std::vector<uint8_t> output;
27
0
   DER_Encoder(output).encode(n_buf, 4, OCTET_STRING);
28
0
   return output;
29
0
   }
30
31
}
32
33
size_t X942_PRF::kdf(uint8_t key[], size_t key_len,
34
                     const uint8_t secret[], size_t secret_len,
35
                     const uint8_t salt[], size_t salt_len,
36
                     const uint8_t label[], size_t label_len) const
37
0
   {
38
0
   std::unique_ptr<HashFunction> hash(HashFunction::create("SHA-160"));
39
0
40
0
   secure_vector<uint8_t> h;
41
0
   secure_vector<uint8_t> in;
42
0
   size_t offset = 0;
43
0
   uint32_t counter = 1;
44
0
45
0
   in.reserve(salt_len + label_len);
46
0
   in += std::make_pair(label,label_len);
47
0
   in += std::make_pair(salt,salt_len);
48
0
49
0
   while(offset != key_len && counter)
50
0
      {
51
0
      hash->update(secret, secret_len);
52
0
53
0
      hash->update(
54
0
         DER_Encoder().start_cons(SEQUENCE)
55
0
56
0
            .start_cons(SEQUENCE)
57
0
               .encode(m_key_wrap_oid)
58
0
               .raw_bytes(encode_x942_int(counter))
59
0
            .end_cons()
60
0
61
0
            .encode_if(salt_len != 0,
62
0
               DER_Encoder()
63
0
                  .start_explicit(0)
64
0
                     .encode(in, OCTET_STRING)
65
0
                  .end_explicit()
66
0
               )
67
0
68
0
            .start_explicit(2)
69
0
               .raw_bytes(encode_x942_int(static_cast<uint32_t>(8 * key_len)))
70
0
            .end_explicit()
71
0
72
0
         .end_cons().get_contents()
73
0
         );
74
0
75
0
      hash->final(h);
76
0
      const size_t copied = std::min(h.size(), key_len - offset);
77
0
      copy_mem(&key[offset], h.data(), copied);
78
0
      offset += copied;
79
0
80
0
      ++counter;
81
0
      }
82
0
83
   // FIXME: returns truncated output
84
0
   return offset;
85
0
   }
86
87
std::string X942_PRF::name() const
88
0
   {
89
0
   return "X9.42-PRF(" + m_key_wrap_oid.to_formatted_string() + ")";
90
0
   }
91
92
}