Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
timesigner.php
1<?php
3
6
13{
15 protected $signer = null;
16
22 public function __construct(SigningAlgorithm $algorithm = null)
23 {
24 $this->signer = new Signer($algorithm);
25 }
26
34 public function setKey($value)
35 {
36 $this->signer->setKey($value);
37 return $this;
38 }
39
45 public function getSeparator()
46 {
47 return $this->signer->getSeparator();
48 }
49
57 public function setSeparator($value)
58 {
59 $this->signer->setSeparator($value);
60 return $this;
61 }
62
81 public function sign($value, $time, $salt = null)
82 {
83 $timestamp = $this->getTimeStamp($time);
84 $signature = $this->getSignature($value, $timestamp, $salt);
85 return $this->pack(array($value, $timestamp, $signature));
86 }
87
127 public function unsign($signedValue, $salt = null)
128 {
129 $timedValue = $this->signer->unsign($signedValue, $salt);
130
131 if (mb_strpos($signedValue, $timedValue) === false)
132 throw new BadSignatureException('Timestamp missing');
133
134 list($value, $time) = $this->unpack($timedValue);
135 $time = (int) $time;
136
137 if ($time <= 0)
138 throw new BadSignatureException(sprintf('Malformed timestamp %d', $time));
139
140 if ($time < time())
141 throw new BadSignatureException(sprintf('Signature timestamp expired (%d < %d)', $time, time()));
142
143 return $value;
144 }
145
155 public function getSignature($value, $timestamp, $salt = null)
156 {
157 if (!is_string($value))
158 throw new ArgumentTypeException('value', 'string');
159
160 $timedValue = $this->pack(array($value, $timestamp));
161 return $this->signer->getSignature($timedValue, $salt);
162 }
163
173 public function validate($value, $timestamp, $signature, $salt = null)
174 {
175 try
176 {
177 $signedValue = $this->pack(array($value, $timestamp, $signature));
178 $this->unsign($signedValue, $salt);
179 return true;
180 }
181 catch(BadSignatureException $e)
182 {
183 return false;
184 }
185 }
186
195 protected function getTimeStamp($time)
196 {
197 if (!is_string($time) && !is_int($time))
198 throw new ArgumentTypeException('time');
199
200 if (is_string($time) && !is_numeric($time))
201 {
202 $timestamp = strtotime($time);
203 if (!$timestamp)
204 throw new ArgumentException(sprintf('Invalid time "%s" format. See "Date and Time Formats"', $time));
205 }
206 else
207 {
208 $timestamp = (int) $time;
209 }
210
211 if ($timestamp < time())
212 throw new ArgumentException(sprintf('Timestamp %d must be greater than now()', $timestamp));
213
214 return $timestamp;
215 }
216
224 public function pack(array $values)
225 {
226 return $this->signer->pack($values);
227 }
228
248 public function unpack($value, $limit = 2)
249 {
250 return $this->signer->unpack($value, $limit);
251 }
252}
getSignature($value, $timestamp, $salt=null)
unsign($signedValue, $salt=null)
sign($value, $time, $salt=null)
validate($value, $timestamp, $signature, $salt=null)
__construct(SigningAlgorithm $algorithm=null)