1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the tiqr project. |
5
|
|
|
* |
6
|
|
|
* The tiqr project aims to provide an open implementation for |
7
|
|
|
* authentication using mobile devices. It was initiated by |
8
|
|
|
* SURFnet and developed by Egeniq. |
9
|
|
|
* |
10
|
|
|
* More information: http://www.tiqr.org |
11
|
|
|
* |
12
|
|
|
* @author Ivo Jansch <[email protected]> |
13
|
|
|
* |
14
|
|
|
* @package tiqr |
15
|
|
|
* |
16
|
|
|
* @license New BSD License - See LICENSE file for details. |
17
|
|
|
* |
18
|
|
|
* @copyright (C) 2010-2011 SURFnet BV |
19
|
|
|
*/ |
20
|
|
|
|
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* A class implementing secure random number generation. |
24
|
|
|
* If openssl functionality is available, openssl is used to generate |
25
|
|
|
* secure random data, if not, a twisted sha1 hash of a random number is used. |
26
|
|
|
* |
27
|
|
|
* @author ivo |
28
|
|
|
* |
29
|
|
|
*/ |
30
|
|
|
class Tiqr_Random |
31
|
|
|
{ |
32
|
|
|
/** |
33
|
|
|
* Generate $length random bytes. |
34
|
|
|
* |
35
|
|
|
* Code courtesy of http://www.zimuel.it/blog/2011/01/strong-cryptography-in-php/ |
36
|
|
|
* |
37
|
|
|
* @param int $length the number of bytes to generate. |
38
|
|
|
*/ |
39
|
2 |
|
public static function randomBytes($length) |
40
|
|
|
{ |
41
|
2 |
|
if(function_exists('openssl_random_pseudo_bytes')) { |
42
|
2 |
|
$rnd = openssl_random_pseudo_bytes($length, $strong); |
43
|
2 |
|
if($strong === TRUE && $rnd !== FALSE) { |
44
|
2 |
|
return $rnd; |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
// When openssl_random_pseudo_bytes failed, fall back on a mt_rand based string. |
49
|
|
|
|
50
|
|
|
$rnd=''; |
51
|
|
|
|
52
|
|
|
for ($i=0;$i<$length;$i++) { |
53
|
|
|
$sha= sha1(mt_rand()); |
54
|
|
|
$char= mt_rand(0,30); |
55
|
|
|
$rnd.= chr(hexdec($sha[$char].$sha[$char+1])); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $rnd; |
59
|
|
|
|
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Generate a random hex string of a certain length. |
64
|
|
|
* @param int $length the desired length of the string |
65
|
|
|
*/ |
66
|
2 |
|
public static function randomHexString($length) |
67
|
|
|
{ |
68
|
2 |
|
$result = bin2hex(self::randomBytes($length)); |
69
|
2 |
|
return $result; |
70
|
|
|
} |
71
|
|
|
} |