Commit | Line | Data |
---|---|---|
14d4f286 S |
1 | <?php |
2 | /** | |
3 | * An implementation of the RFC 10833-2 KDF3 Standard key derivation function | |
4 | * | |
5 | * PHP version 5.3 | |
6 | * | |
7 | * @category PHPCryptLib | |
8 | * @package Key | |
9 | * @subpackage Derivation | |
10 | * @author Anthony Ferrara <ircmaxell@ircmaxell.com> | |
11 | * @copyright 2011 The Authors | |
12 | * @license http://www.opensource.org/licenses/mit-license.html MIT License | |
13 | * @version Build @@version@@ | |
14 | */ | |
15 | ||
16 | namespace CryptLib\Key\Derivation\KDF; | |
17 | ||
18 | use CryptLib\Hash\Hash; | |
19 | ||
20 | /** | |
21 | * An implementation of the RFC 10833-2 KDF3 Standard key derivation function | |
22 | * | |
23 | * @category PHPCryptLib | |
24 | * @package Key | |
25 | * @subpackage Derivation | |
26 | * @author Anthony Ferrara <ircmaxell@ircmaxell.com> | |
27 | */ | |
28 | class KDF3 | |
29 | extends \CryptLib\Key\Derivation\AbstractDerivation | |
30 | implements \CryptLib\Key\Derivation\KDF | |
31 | { | |
32 | ||
33 | /** | |
34 | * @var array An array of options for the key derivation function | |
35 | */ | |
36 | protected $options = array( | |
37 | 'hash' => 'sha512', | |
38 | 'pAmt' => 4, | |
39 | ); | |
40 | ||
41 | /** | |
42 | * Derive a key of the specified length based on the inputted secret | |
43 | * | |
44 | * @param string $secret The secret to base the key on | |
45 | * @param int $length The length of the key to derive | |
46 | * @param string $other Additional data to append to the key | |
47 | * | |
48 | * @return string The generated key | |
49 | */ | |
50 | public function derive($secret, $length, $other = '') { | |
51 | $size = Hash::getHashSize($this->hash); | |
52 | $len = ceil($length / $size); | |
53 | $res = ''; | |
54 | $stub = str_repeat(chr(0), max($this->options['pAmt'], 0)); | |
55 | for ($i = 0; $i < $len; $i++) { | |
56 | $tmp = $stub . pack('N', $i); | |
57 | $res .= hash($this->hash, $tmp . $secret . $other, true); | |
58 | } | |
59 | return substr($res, 0, $length); | |
60 | } | |
61 | ||
62 | } | |
63 |