Botan 1.10.17
prf_x942.cpp
Go to the documentation of this file.
1/*
2* X9.42 PRF
3* (C) 1999-2007 Jack Lloyd
4*
5* Distributed under the terms of the Botan license
6*/
7
8#include <botan/prf_x942.h>
9#include <botan/der_enc.h>
10#include <botan/oids.h>
11#include <botan/sha160.h>
12#include <botan/loadstor.h>
13#include <algorithm>
14#include <memory>
15
16namespace Botan {
17
18namespace {
19
20/*
21* Encode an integer as an OCTET STRING
22*/
23MemoryVector<byte> encode_x942_int(u32bit n)
24 {
25 byte n_buf[4] = { 0 };
26 store_be(n, n_buf);
27 return DER_Encoder().encode(n_buf, 4, OCTET_STRING).get_contents();
28 }
29
30}
31
32/*
33* X9.42 PRF
34*/
36 const byte secret[], size_t secret_len,
37 const byte salt[], size_t salt_len) const
38 {
39 SHA_160 hash;
40 const OID kek_algo(key_wrap_oid);
41
43 u32bit counter = 1;
44
45 while(key.size() != key_len && counter)
46 {
47 hash.update(secret, secret_len);
48
49 hash.update(
50 DER_Encoder().start_cons(SEQUENCE)
51
52 .start_cons(SEQUENCE)
53 .encode(kek_algo)
54 .raw_bytes(encode_x942_int(counter))
55 .end_cons()
56
57 .encode_if(salt_len != 0,
59 .start_explicit(0)
60 .encode(salt, salt_len, OCTET_STRING)
61 .end_explicit()
62 )
63
64 .start_explicit(2)
65 .raw_bytes(encode_x942_int(static_cast<u32bit>(8 * key_len)))
66 .end_explicit()
67
68 .end_cons().get_contents()
69 );
70
71 SecureVector<byte> digest = hash.final();
72 const size_t needed = std::min(digest.size(), key_len - key.size());
73 key += std::make_pair(&digest[0], needed);
74
75 ++counter;
76 }
77
78 return key;
79 }
80
81/*
82* X9.42 Constructor
83*/
84X942_PRF::X942_PRF(const std::string& oid)
85 {
86 if(OIDS::have_oid(oid))
87 key_wrap_oid = OIDS::lookup(oid).as_string();
88 else
89 key_wrap_oid = oid;
90 }
91
92}
void update(const byte in[], size_t length)
Definition buf_comp.h:33
void final(byte out[])
Definition buf_comp.h:80
SecureVector< byte > get_contents()
Definition der_enc.cpp:122
DER_Encoder & encode(bool b)
Definition der_enc.cpp:209
size_t size() const
Definition secmem.h:29
SecureVector< byte > derive(size_t, const byte[], size_t, const byte[], size_t) const
Definition prf_x942.cpp:35
X942_PRF(const std::string &oid)
Definition prf_x942.cpp:84
std::string lookup(const OID &oid)
Definition oids.cpp:31
bool have_oid(const std::string &name)
Definition oids.cpp:61
@ SEQUENCE
Definition asn1_int.h:35
@ OCTET_STRING
Definition asn1_int.h:31
unsigned int u32bit
Definition types.h:32
void store_be(u16bit in, byte out[2])
Definition loadstor.h:412