RandomGenerator::randomToken()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 3
rs 10
nc 1
cc 1
eloc 2
nop 1
1
<?php
2
/**
3
 * Generates entropy values based on strongest available methods
4
 * (mcrypt_create_iv(), openssl_random_pseudo_bytes(), /dev/urandom, COM.CAPICOM.Utilities.1, mt_rand()).
5
 * Chosen method depends on operating system and PHP version.
6
 *
7
 * Shamelessly stolen from https://raw.githubusercontent.com/silverstripe/silverstripe-framework/3.1/security/RandomGenerator.php
8
 */
9
class RandomGenerator {
10
11
	/**
12
	 * Note: Returned values are not guaranteed to be crypto-safe,
13
	 * depending on the used retrieval method.
14
	 * 
15
	 * @return string Returns a random series of bytes
16
	 */
17
	public function generateEntropy() {
18
		$isWin = preg_match('/WIN/', PHP_OS);
19
		
20
		// TODO Fails with "Could not gather sufficient random data" on IIS, temporarily disabled on windows
21
		if(!$isWin) {
22
			if(function_exists('mcrypt_create_iv')) {
23
				$e = mcrypt_create_iv(64, MCRYPT_DEV_URANDOM);
24
				if($e !== false) return $e;
25
			}
26
		}
27
28
		// Fall back to SSL methods - may slow down execution by a few ms
29
		if (function_exists('openssl_random_pseudo_bytes')) {
30
			$e = openssl_random_pseudo_bytes(64, $strong);
31
			// Only return if strong algorithm was used
32
			if($strong) return $e;
33
		}
34
35
		// Read from the unix random number generator
36
		if(!$isWin && !ini_get('open_basedir') && is_readable('/dev/urandom') && ($h = fopen('/dev/urandom', 'rb'))) {
37
			$e = fread($h, 64);
38
			fclose($h);
39
			return $e;
40
		}
41
42
		// Warning: Both methods below are considered weak
43
44
		// try to read from the windows RNG
45
		if($isWin && class_exists('COM')) {
46
			try {
47
				$comObj = new COM('CAPICOM.Utilities.1');
48
49
				if(is_callable(array($comObj,'GetRandom'))) {
50
					return  base64_decode($comObj->GetRandom(64, 0));
51
				}
52
			} catch (Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
53
			}
54
		}
55
56
		// Fallback to good old mt_rand()
57
		return uniqid(mt_rand(), true);
58
	}
59
60
	/**
61
	 * Generates a random token that can be used for session IDs, CSRF tokens etc., based on
62
	 * hash algorithms.
63
	 *
64
	 * If you are using it as a password equivalent (e.g. autologin token) do NOT store it 
65
	 * in the database as a plain text but encrypt it with Member::encryptWithUserSettings.
66
	 * 
67
	 * @param String $algorithm Any identifier listed in hash_algos() (Default: whirlpool)
68
	 *
69
	 * @return String Returned length will depend on the used $algorithm
70
	 */
71
	public function randomToken($algorithm = 'whirlpool') {
72
		return hash($algorithm, $this->generateEntropy());
73
	}
74
}