aboutsummaryrefslogtreecommitdiff
path: root/pwhash.php
blob: 8ec47628dba9e39a47b42322c6649983974e123d (plain)
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
<?php
/*
 * File: ratatoeskr/sys/pwhash.php
 * 
 * Hashing passwords
 * 
 * License:
 * This file is part of Ratatöskr.
 * Ratatöskr is licensed unter the MIT / X11 License.
 * See "ratatoeskr/licenses/ratatoeskr" for more information.
 */

/*
 * Class: PasswordHash
 * Contains static functions for password hashes.
 * Is just used as a namespace, can not be created.
 * 
 * It should be fairly difficult to break these salted hashes via bruteforce attacks.
 */
class PasswordHash
{
	private function __construct() {} /* Prevent construction */
	
	private static $saltlen_min = 20;
	private static $saltlen_max = 30;
	private static $iterations_min = 200;
	private static $iterations_max = 1000;
	
	private static function hash($data, $salt, $iterations)
	{
		$hash = $data . $salt;
		for($i = $iterations ;$i--;)
			$hash = sha1($data . $hash . $salt, (bool) $i);
		return $iterations . '$' . bin2hex($salt) . '$' . $hash;
	}
	
	/*
	 * Function: create
	 * Create a password hash string.
	 * 
	 * Parameters:
	 * 	$password - The password (or other data) to hash.
	 * 
	 * Returns:
	 * 	The salted hash as a string.
	 */
	public static function create($password)
	{
		$salt = "";
		$saltlen = mt_rand(self::$saltlen_min, self::$saltlen_max);
		for($i = 0; $i < $saltlen; $i++)
			$salt .= chr(mt_rand(0,255));
		return self::hash($password, $salt, mt_rand(self::$iterations_min, self::$iterations_max));
	}
	
	/*
	 * Function: validate
	 * Validate a salted hash.
	 * 
	 * Parameters:
	 * 	$password - The password to test.
	 * 	$pwhash   - The hash to test against.
	 * 
	 * Returns:
	 * 	True, if $password was correct, False otherwise.
	 */
	public static function validate($password, $pwhash)
	{
		list($iterations, $hexsalt, $hash) = explode('$', $pwhash);
		return self::hash($password, pack("H*", $hexsalt), $iterations) == $pwhash;
	}
}

?>