/
security.php
75 lines (63 loc) · 2.3 KB
/
security.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
class security
{
static function initialize($algorithm, $salt)
{
self::$algorithm = $algorithm;
self::$salt = $salt;
}
static function wrap($mixed, $domain, $expire_at, $address = null)
{
$package =
[
'value' => $mixed,
'domain' => $domain,
'expire_at' => $expire_at
];
is_null($address) or $package['address'] = $address;
$package['digest'] = self::digest($package);
return base64_encode(json::encode($package));
}
static function unwrap($token, $domains, $address = null)
{
if($package = base64_decode($token, true))
{
if($package = json::decode($package))
{
if(isset($package->value) and isset($package->domain) and isset($package->expire_at) and isset($package->digest))
{
$digest = $package->digest;
unset($package->digest);
if($digest === self::digest($package))
{
if(isset($package->address))
{
if(is_null($address) or $package->address !== $address)
{
return null;
}
}
if($package->expire_at === 0 or $package->expire_at > @time())
{
foreach($domains as $domain)
{
if(ends_with('.' . $package->domain, '.' . $domain))
{
return $package->value;
}
}
}
}
}
}
}
return null;
}
private static function digest($mixed)
{
return hash_hmac(self::$algorithm, json::encode($mixed), self::$salt);
}
private static $algorithm = 'md5'; # http://www.php.net/manual/en/function.hash-algos.php
private static $salt = 'Initialize salt by calling security::initialize at the beginning of your main script';
}
?>