Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
119 - 1
<?php
2
 
3
/**
4
 *
5
 * A tiny Nonce generator with variable time-outs.
6
 *
7
 * No database required.
8
 * Each Nonce has its own Salt.
9
 *
10
 */
11
class NonceUtil {
12
 
13
    /**
14
     * Generate a Nonce.
15
     *
16
     * The generated string contains three parts, seperated by a comma.
17
     * The first part is the individual salt. The seconds part is the
18
     * time until the nonce is valid. The third part is a hash of the
19
     * salt, the time, and a secret value.
20
     *
21
     * @param $secret required String with at least 10 characters. The
22
     * same value must be passed to check().
23
     *
24
     * @param $timeoutSeconds the time in seconds until the nonce
25
     * becomes invalid.
26
     *
27
     * @return string the generated Nonce.
28
     *
29
     */
30
    public static function generate($secret, $timeoutSeconds = 180) {
31
        if (is_string($secret) == false || strlen($secret) < 10) {
32
            throw new InvalidArgumentException("missing valid secret");
33
        }
34
        $salt = self::generateSalt();
35
        $time = time();
36
        $maxTime = $time + $timeoutSeconds;
37
        $nonce = $salt . "," . $maxTime . "," . sha1($salt . $secret . $maxTime);
38
        return $nonce;
39
    }
40
 
41
    /**
42
     * Check a previously generated Nonce.
43
     *
44
     * @param $secret the secret string passed to generate().
45
     *
46
     * @returns bool whether the Nonce is valid.
47
     */
48
    public static function check($secret, $nonce) {
49
        if (is_string($nonce) == false) {
50
            return false;
51
        }
52
        $a = explode(',', $nonce);
53
        if (count($a) != 3) {
54
            return false;
55
        }
56
        $salt = $a[0];
57
        $maxTime = intval($a[1]);
58
        $hash = $a[2];
59
        $back = sha1($salt . $secret . $maxTime);
60
        if ($back != $hash) {
61
            return false;
62
        }
63
        if (time() > $maxTime) {
64
            return false;
65
        }
66
        return true;
67
    }
68
 
69
    private static function generateSalt() {
70
        $length = 10;
71
        $chars = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
72
        $ll = strlen($chars) - 1;
73
        $o = '';
74
        while (strlen($o) < $length) {
75
            $o .= $chars[rand(0, $ll) ];
76
        }
77
        return $o;
78
    }
79
 
80
}
81
 
82
?>