Completed
Pull Request — master (#526)
by Michael
16:45 queued 06:57
created

AuthUtility   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 72.21%

Importance

Changes 0
Metric Value
dl 0
loc 87
rs 10
c 0
b 0
f 0
ccs 13
cts 18
cp 0.7221
wmc 10
lcom 0
cbo 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A encryptVersion2() 0 3 1
A encryptVersion1() 0 3 1
A verifyVersion2() 0 3 1
A testCredentials() 0 29 5
A isCredentialVersionLatest() 0 3 1
A encryptPassword() 0 3 1
1
<?php
2
3
class AuthUtility
4
{
5
	/**
6
	 * Test the specified data against the specified credentials
7
	 * @param string $password
8
	 * @param string $credentials
9
	 * @return bool
10
	 */
11
	public static function testCredentials($password, $credentials)
12
	{
13
		global $minimumPasswordVersion;
14
15
		if (substr($credentials, 0, 1) != ":") {
16
			return false;
17
		}
18
19
		// determine password version
20
		$data = explode(':', substr($credentials, 1));
21
22
		// call the encryptVersion function for the version that this password actually is.
23
		// syntax: :1:SALT:HASH
24
		// syntax: :2:x:HASH
25
26
		// check the version is one of the allowed ones:
27
		if ($minimumPasswordVersion > $data[0]) {
28
			return false;
29
		}
30
31
		if ($data[0] == 1) {
32
			return $credentials == self::encryptVersion1($password, $data[1]);
33
		}
34
35
		if ($data[0] == 2) {
36
			return self::verifyVersion2($password, $data[2]);
37
		}
38
39
		return false;
40
	}
41
42
	/**
43
	 * @param string $credentials
44
	 * @return bool
45
	 */
46
	public static function isCredentialVersionLatest($credentials)
47
	{
48
		return substr($credentials, 0, 3) === ":2:";
49
	}
50
51
	/**
52
	 * Encrypts a user's password with the latest version of the hash algorithm
53
	 * @param string $password
54
	 * @return string
55
	 */
56
	public static function encryptPassword($password)
57
	{
58
		return self::encryptVersion2($password);
59
	}
60
61
	/**
62
	 * @param string $password
63
	 * @param string $salt
64
	 * @return string
65
	 */
66
	private static function encryptVersion1($password, $salt)
67
	{
68
		return ':1:' . $salt . ':' . md5($salt . '-' . md5($password));
69
	}
70
71
	/**
72
	 * @param string $password
73
	 * @return string
74
	 */
75
	private static function encryptVersion2($password)
76
	{
77
		return ':2:x:' . password_hash($password, PASSWORD_BCRYPT);
78
	}
79
80
	/**
81
	 * @param string $password
82
	 * @param string $hash
83
	 * @return bool
84
	 */
85
	private static function verifyVersion2($password, $hash)
86
	{
87
		return password_verify($password, $hash);
88
	}
89
}
90