-
Notifications
You must be signed in to change notification settings - Fork 2
/
functions.php
70 lines (59 loc) · 1.44 KB
/
functions.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
<?php
namespace MNC\Fernet\UrlBase64;
use MNC\Fernet\UnexpectedError;
/**
* @param string $data
* @return string
*/
function encode(string $data): string
{
return str_replace(['+', '/'], ['-', '_'], base64_encode($data));
}
/**
* @param string $base64
* @return string
*
* @throws UnexpectedError if there is a problem decoding the string
*/
function decode(string $base64): string
{
$result = base64_decode(str_replace(['-', '_'], ['+', '/'], $base64), true);
if (!is_string($result)) {
throw new UnexpectedError('Invalid url encoded base64 string provided');
}
return $result;
}
namespace MNC\Fernet\Str;
use Exception;
use InvalidArgumentException;
use MNC\Fernet\UnexpectedError;
/**
* Pads a message to a multiple of 16 bytes.
*
* @param string $message
*
* @return string
*/
function pad(string $message): string
{
$pad = 16 - (strlen($message) % 16);
$message .= str_repeat(chr($pad), $pad);
return $message;
}
/**
* Removes the padding of a message.
*
* @param string $paddedMessage
*
* @return string
* @throws InvalidArgumentException on padding error
* @throws UnexpectedError if un-padding fails
*/
function unpad(string $paddedMessage): string
{
$pad = ord($paddedMessage[strlen($paddedMessage) - 1]);
if ($pad !== substr_count(substr($paddedMessage, -$pad), chr($pad))) {
throw new UnexpectedError('Padding error');
}
return substr($paddedMessage, 0, -$pad);
}