monotone

monotone Mtn Source Tree

Root/botan/prf_x942.cpp

1/*************************************************
2* X9.42 PRF Source File *
3* (C) 1999-2006 The Botan Project *
4*************************************************/
5
6#include <botan/kdf.h>
7#include <botan/der_enc.h>
8#include <botan/oids.h>
9#include <botan/lookup.h>
10#include <botan/bit_ops.h>
11#include <algorithm>
12#include <memory>
13
14namespace Botan {
15
16namespace {
17
18/*************************************************
19* Encode an integer as an OCTET STRING *
20*************************************************/
21MemoryVector<byte> encode_x942_int(u32bit n)
22 {
23 byte n_buf[4] = { 0 };
24 for(u32bit j = 0; j != 4; ++j)
25 n_buf[j] = get_byte(j, n);
26
27 return DER_Encoder().encode(n_buf, 4, OCTET_STRING).get_contents();
28 }
29
30}
31
32/*************************************************
33* X9.42 PRF *
34*************************************************/
35SecureVector<byte> X942_PRF::derive(u32bit key_len,
36 const byte secret[], u32bit secret_len,
37 const byte salt[], u32bit salt_len) const
38 {
39 std::auto_ptr<HashFunction> hash(get_hash("SHA-1"));
40 const OID kek_algo(key_wrap_oid);
41
42 SecureVector<byte> key;
43 u32bit counter = 1;
44
45 while(key.size() != key_len)
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,
58 DER_Encoder()
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(8 * key_len))
66 .end_explicit()
67
68 .end_cons().get_contents()
69 );
70
71 SecureVector<byte> digest = hash->final();
72 key.append(digest, std::min(digest.size(), key_len - key.size()));
73
74 ++counter;
75 }
76
77 return key;
78 }
79
80/*************************************************
81* X9.42 Constructor *
82*************************************************/
83X942_PRF::X942_PRF(const std::string& oid)
84 {
85 if(OIDS::have_oid(oid))
86 key_wrap_oid = OIDS::lookup(oid).as_string();
87 else
88 key_wrap_oid = oid;
89 }
90
91}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status