Passed
Push — develop ( 22eefe...e65dcd )
by Pieter van der
06:04
created

Tiqr_Random   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 57.14%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 6
eloc 13
c 2
b 0
f 0
dl 0
loc 40
ccs 8
cts 14
cp 0.5714
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A randomHexString() 0 4 1
A randomBytes() 0 20 5
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]));
0 ignored issues
show
Bug introduced by
It seems like hexdec($sha[$char] . $sha[$char + 1]) can also be of type double; however, parameter $codepoint of chr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

55
            $rnd.= chr(/** @scrutinizer ignore-type */ hexdec($sha[$char].$sha[$char+1]));
Loading history...
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
}