Botan 1.10.17

pbkdf2.cpp
Go to the documentation of this file.
1 /*
2 * PBKDF2
3 * (C) 1999-2007 Jack Lloyd
4 *
5 * Distributed under the terms of the Botan license
6 */
7
8 #include <botan/pbkdf2.h>
9 #include <botan/get_byte.h>
10 #include <botan/internal/xor_buf.h>
11
12 namespace Botan {
13
14 /*
15 * Return a PKCS #5 PBKDF2 derived key
16 */
17 OctetString PKCS5_PBKDF2::derive_key(size_t key_len,
18 const std::string& passphrase,
19 const byte salt[], size_t salt_size,
20 size_t iterations) const
21 {
22 if(iterations == 0)
23 throw Invalid_Argument("PKCS#5 PBKDF2: Invalid iteration count");
24
25 try
26 {
27 mac->set_key(reinterpret_cast<const byte*>(passphrase.data()),
28 passphrase.length());
29 }
30 catch(Invalid_Key_Length)
31 {
32 throw Exception(name() + " cannot accept passphrases of length " +
33 to_string(passphrase.length()));
34 }
35
36 SecureVector<byte> key(key_len);
37
38 byte* T = &key[0];
39
40 SecureVector<byte> U(mac->output_length());
41
42 u32bit counter = 1;
43 while(key_len)
44 {
45 size_t T_size = std::min<size_t>(mac->output_length(), key_len);
46
47 mac->update(salt, salt_size);
48 mac->update_be(counter);
49 mac->final(&U[0]);
50
51 xor_buf(T, U, T_size);
52
53 for(size_t j = 1; j != iterations; ++j)
54 {
55 mac->update(U);
56 mac->final(&U[0]);
57 xor_buf(T, U, T_size);
58 }
59
60 key_len -= T_size;
61 T += T_size;
62 ++counter;
63 }
64
65 return key;
66 }
67
68 }
Botan::Invalid_Key_Length
Definition: exceptn.h:55
Botan::OctetString
Definition: symkey.h:19
Botan::Invalid_Argument
std::invalid_argument Invalid_Argument
Definition: exceptn.h:20
Botan::PKCS5_PBKDF2::name
std::string name() const
Definition: pbkdf2.h:22
Botan::byte
unsigned char byte
Definition: types.h:22
Botan::SymmetricAlgorithm::set_key
void set_key(const SymmetricKey &key)
Definition: sym_algo.h:60
Botan::Buffered_Computation::update
void update(const byte in[], size_t length)
Definition: buf_comp.h:33
Botan::Exception
std::runtime_error Exception
Definition: exceptn.h:19
Botan
Definition: algo_base.h:14
Botan::Buffered_Computation::final
void final(byte out[])
Definition: buf_comp.h:80
Botan::to_string
std::string to_string(u64bit n, size_t min_len)
Definition: parsing.cpp:42
Botan::SecureVector< byte >
Botan::PKCS5_PBKDF2::derive_key
OctetString derive_key(size_t output_len, const std::string &passphrase, const byte salt[], size_t salt_len, size_t iterations) const
Definition: pbkdf2.cpp:17
Botan::Buffered_Computation::update_be
void update_be(const T in)
Definition: buf_comp.h:48
Botan::xor_buf
void xor_buf(byte out[], const byte in[], size_t length)
Definition: xor_buf.h:21
Botan::Buffered_Computation::output_length
virtual size_t output_length() const =0
Botan::u32bit
unsigned int u32bit
Definition: types.h:32