forked from arzzen/php-time-lock-encryption
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimeLockCrypt.php
142 lines (124 loc) · 2.47 KB
/
TimeLockCrypt.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<?php
require "fernet-php/src/Fernet.php";
use Fernet\Fernet;
/**
* Time Lock Encryption Class
*
* @author Lukas Mestan
* @copyright GPL v2
* @see http://www.gwern.net/Self-decrypting files
* @see http://people.csail.mit.edu/rivest/lcs35-puzzle-description.txt
* @see https://github.com/kelvinmo/fernet-php
* @version 1.0.0
*/
class TimeLockCrypt
{
/**
* Count of iterations
*
* @access private
* @var integer
*/
private $iterations = 0;
/**
* Keyseed
*
* @access private
* @var string
*/
private $keyseed = '';
/**
* Signing key
*
* @access private
* @var string
*/
private $signing_key = '';
/**
* Class contructor
*
* @access public
* @param string $keyseed
*/
public function __construct($keyseed)
{
$this->keyseed = $keyseed;
$this->signing_key = substr($keyseed, 0, 16);
}
/**
* Encrypt message
*
* @access public
* @param string $delta
* @param string $message
* @return string
*/
public function encrypt($delta, $message)
{
$key = $this->generateByTime($this->keyseed, $delta);
$fernet = new Fernet($key);
return $fernet->encode($message);
}
/**
* Decrypt message
*
* @access public
* @param string $encrypted
* @param integer $iterations
* @return string
*/
public function decrypt($encrypted, $iterations)
{
$key = $this->generateByIterations($this->keyseed, $iterations);
$fernet = new Fernet($key);
return $fernet->decode($encrypted);
}
/**
* Iterations number
*
* @access public
* @return integer
*/
public function getIterations()
{
return $this->iterations;
}
/**
* Generate key by iterations
*
* @access private
* @param string $seed
* @param integer $iters
* @return string
*/
private function generateByIterations($seed, $iters)
{
$hash = hash_hmac("sha256", $seed, $this->signing_key, TRUE);
foreach(range(1, $iters) as $x)
{
$hash = hash_hmac("sha256", $hash, $this->signing_key, TRUE);
}
return Fernet::base64url_encode($hash);
}
/**
* Generate key by time
*
* @access private
* @param string $seed
* @param integer|string $delta strtotime
* @return string
*/
private function generateByTime($seed, $delta)
{
$end = strtotime($delta);
$hash = hash_hmac("sha256", $seed, $this->signing_key, TRUE);
$iters = 0;
while(time() < $end)
{
$hash = hash_hmac("sha256", $hash, $this->signing_key, TRUE);
$iters += 1;
}
$this->iterations = $iters;
return Fernet::base64url_encode($hash);
}
}