1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
/*
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/botan.h>
#include <botan/pbkdf2.h>
#include <botan/hmac.h>
#include <botan/sha160.h>
#include <iostream>
#include <memory>
using namespace Botan;
std::string password_hash(const std::string& pass,
RandomNumberGenerator& rng);
bool password_hash_ok(const std::string& pass, const std::string& hash);
int main(int argc, char* argv[])
{
if(argc != 2 && argc != 3)
{
std::cerr << "Usage: " << argv[0] << " password\n";
std::cerr << "Usage: " << argv[0] << " password hash\n";
return 1;
}
Botan::LibraryInitializer init;
try
{
if(argc == 2)
{
AutoSeeded_RNG rng;
std::cout << "H('" << argv[1] << "') = "
<< password_hash(argv[1], rng) << '\n';
}
else
{
bool ok = password_hash_ok(argv[1], argv[2]);
if(ok)
std::cout << "Password and hash match\n";
else
std::cout << "Password and hash do not match\n";
}
}
catch(std::exception& e)
{
std::cerr << e.what() << '\n';
return 1;
}
return 0;
}
const u32bit SALT_BYTES = 8; // 64 bits of salt
const u32bit PBKDF_OUTPUT_LEN = 16; // 128 bits output
const u32bit KDF_ITERATIONS = 100000;
std::string password_hash(const std::string& pass,
RandomNumberGenerator& rng)
{
PKCS5_PBKDF2 kdf(new HMAC(new SHA_160));
SecureVector<byte> salt(SALT_BYTES);
rng.randomize(&salt[0], salt.size());
// Encode the salt plus 96 bits of PBKDF2 output
Pipe pipe(new Base64_Encoder);
pipe.start_msg();
pipe.write(salt);
pipe.write(kdf.derive_key(PBKDF_OUTPUT_LEN, pass,
&salt[0], salt.size(),
KDF_ITERATIONS).bits_of());
pipe.end_msg();
return pipe.read_all_as_string();
}
bool password_hash_ok(const std::string& pass, const std::string& hash)
{
Pipe pipe(new Base64_Decoder);
pipe.start_msg();
pipe.write(hash);
pipe.end_msg();
SecureVector<byte> hash_bin = pipe.read_all();
if(hash_bin.size() != (PBKDF_OUTPUT_LEN + SALT_BYTES))
return false;
PKCS5_PBKDF2 kdf(new HMAC(new SHA_160));
SecureVector<byte> cmp = kdf.derive_key(
PBKDF_OUTPUT_LEN, pass,
&hash_bin[0], SALT_BYTES,
KDF_ITERATIONS).bits_of();
return same_mem(cmp.begin(), hash_bin.begin() + 6, 12);
}
|