1 /*******************************************************************************
2 
3     PBKDF2 key derivation wrapper.
4 
5     Requires linking with libgcrypt:
6             -L-lgcrypt
7 
8     Copyright:
9         Copyright (c) 2009-2016 dunnhumby Germany GmbH.
10         All rights reserved.
11 
12     License:
13         Boost Software License Version 1.0. See LICENSE_BOOST.txt for details.
14         Alternatively, this file may be distributed under the terms of the Tango
15         3-Clause BSD License (see LICENSE_BSD.txt for details).
16 
17 *******************************************************************************/
18 
19 module ocean.util.cipher.gcrypt.PBKDF2;
20 
21 
22 import ocean.util.cipher.gcrypt.core.KeyDerivationCore;
23 
24 /*******************************************************************************
25 
26     PBKDF2 with SHA256 hashing wrapper class
27 
28     For a usage example, see the unittests below.
29 
30 *******************************************************************************/
31 
32 public alias KeyDerivationCore!(KDF.GCRY_KDF_PBKDF2, Hasher.GCRY_MD_SHA256) PBKDF2;
33 
34 version (unittest)
35 {
36     import ocean.core.Test;
37     import ocean.text.convert.Hex;
38 }
39 
40 /// PBKDF2 usage example
41 unittest
42 {
43     // Set up the passphrase and salt
44     auto passphrase = cast(immutable(ubyte)[])"passphrase";
45     auto salt = cast(immutable(ubyte)[])"salt";
46 
47     // Create the key derivation instance
48     auto pbkdf2 = new PBKDF2(passphrase, salt);
49 
50     // The number of hashing iterations
51     static immutable ITERATIONS = 256;
52 
53     // The buffer to write the key to, set to the expected key length
54     ubyte[] key_buf;
55     key_buf.length = 32;
56 
57     // Derive the key
58     auto key = pbkdf2.derive(ITERATIONS, key_buf);
59 
60     // The expected key is created so the output of pbkdf2 can be verified
61     static immutable EXPECTED_KEY = "1a0e45a1b7dd26f47b3549c56dca01df2fa27fa50ef799d9165db53b202fa267";
62     ubyte[] expected_key;
63     hexToBin(EXPECTED_KEY, expected_key);
64 
65     test!("==")(key, expected_key);
66 }