1 /**
2 * KDF2
3 * 
4 * Copyright:
5 * (C) 1999-2007 Jack Lloyd
6 * (C) 2014-2015 Etienne Cimon
7 *
8 * License:
9 * Botan is released under the Simplified BSD License (see LICENSE.md)
10 */
11 module botan.kdf.kdf2;
12 
13 import botan.constants;
14 static if (BOTAN_HAS_TLS || BOTAN_HAS_PUBLIC_KEY_CRYPTO):
15 
16 import botan.kdf.kdf;
17 import botan.hash.hash;
18 import botan.utils.types;
19 import std.algorithm : min;
20 
21 /**
22 * KDF2, from IEEE 1363
23 */
24 class KDF2 : KDF
25 {
26 public:
27     /*
28     * KDF2 Key Derivation Mechanism
29     */
30     override SecureVector!ubyte derive(size_t out_len,
31                                const(ubyte)* secret, 
32                                size_t secret_len,
33                                const(ubyte)* P, 
34                                size_t P_len) const
35     {
36         HashFunction hash = cast(HashFunction)*m_hash;
37         SecureVector!ubyte output;
38         uint counter = 1;
39         
40         while (out_len && counter)
41         {
42             hash.update(secret, secret_len);
43             hash.updateBigEndian(counter);
44             hash.update(P, P_len);
45             
46             SecureVector!ubyte hash_result = hash.finished();
47             
48             size_t added = min(hash_result.length, out_len);
49             output ~= hash_result.ptr[0 .. added];
50             out_len -= added;
51             
52             ++counter;
53         }
54         
55         return output;
56     }
57 
58     override @property string name() const { return "KDF2(" ~ m_hash.name ~ ")"; }
59     override KDF clone() const { return new KDF2(m_hash.clone()); }
60 
61     this(HashFunction h) { m_hash = h; }
62 private:
63     Unique!HashFunction m_hash;
64 }