pbkdf2.php
Code (php)
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
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
<?php
/**
* @author Chris Horeweg
* @package Security_Tools
*/
function pbkdf2($password, $salt, $algorithm = 'sha512', $count = 20000, $key_length = 128, $raw_output = false)
{
if(!in_array($algorithm, hash_algos(), true)) {
exit('pbkdf2: Hash algoritme is niet geinstalleerd op het systeem.');
}
if($count <= 0 || $key_length <= 0) {
$count = 20000;
$key_length = 128;
}
$hash_length = strlen(hash($algorithm, "", true));
$block_count = ceil($key_length / $hash_length);
$output = "";
for($i = 1; $i <= $block_count; $i++) {
$last = $salt . pack("N", $i);
$last = $xorsum = hash_hmac($algorithm, $last, $password, true);
for ($j = 1; $j < $count; $j++) {
$xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
}
$output .= $xorsum;
}
if($raw_output) {
return substr($output, 0, $key_length);
}
else {
return base64_encode(substr($output, 0, $key_length));
}
}
/**
* @author Chris Horeweg
* @package Security_Tools
*/
function pbkdf2($password, $salt, $algorithm = 'sha512', $count = 20000, $key_length = 128, $raw_output = false)
{
if(!in_array($algorithm, hash_algos(), true)) {
exit('pbkdf2: Hash algoritme is niet geinstalleerd op het systeem.');
}
if($count <= 0 || $key_length <= 0) {
$count = 20000;
$key_length = 128;
}
$hash_length = strlen(hash($algorithm, "", true));
$block_count = ceil($key_length / $hash_length);
$output = "";
for($i = 1; $i <= $block_count; $i++) {
$last = $salt . pack("N", $i);
$last = $xorsum = hash_hmac($algorithm, $last, $password, true);
for ($j = 1; $j < $count; $j++) {
$xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
}
$output .= $xorsum;
}
if($raw_output) {
return substr($output, 0, $key_length);
}
else {
return base64_encode(substr($output, 0, $key_length));
}
}