|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Copyright 2015 François Kooman <[email protected]>. |
|
5
|
|
|
* |
|
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
|
7
|
|
|
* you may not use this file except in compliance with the License. |
|
8
|
|
|
* You may obtain a copy of the License at |
|
9
|
|
|
* |
|
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
|
11
|
|
|
* |
|
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
|
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
|
14
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
15
|
|
|
* See the License for the specific language governing permissions and |
|
16
|
|
|
* limitations under the License. |
|
17
|
|
|
*/ |
|
18
|
|
|
|
|
19
|
|
|
namespace fkooman\RemoteStorage\Base64; |
|
20
|
|
|
|
|
21
|
|
|
use InvalidArgumentException; |
|
22
|
|
|
|
|
23
|
|
|
class Base64Url extends Base64 |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* Encode to base64url. |
|
27
|
|
|
* |
|
28
|
|
|
* @param string $data the data to encode |
|
29
|
|
|
* |
|
30
|
|
|
* @return string the encoded data |
|
31
|
|
|
*/ |
|
32
|
|
|
public static function encode($data) |
|
33
|
|
|
{ |
|
34
|
|
|
if (!is_string($data)) { |
|
35
|
|
|
throw new InvalidArgumentException('data must be string'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
$encodedData = parent::encode($data); |
|
39
|
|
|
|
|
40
|
|
|
// URL safe replacement and remove padding |
|
41
|
|
|
return rtrim(strtr($encodedData, '+/', '-_'), '='); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Decode base64url. |
|
46
|
|
|
* |
|
47
|
|
|
* @param string $data the data to decode |
|
48
|
|
|
* |
|
49
|
|
|
* @return string the decoded data |
|
50
|
|
|
*/ |
|
51
|
|
|
public static function decode($data) |
|
52
|
|
|
{ |
|
53
|
|
|
if (!is_string($data)) { |
|
54
|
|
|
throw new InvalidArgumentException('data must be string'); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
// undo the URL safe replacement |
|
58
|
|
|
$convertedData = strtr($data, '-_', '+/'); |
|
59
|
|
|
|
|
60
|
|
|
// restore the padding |
|
61
|
|
|
switch (strlen($convertedData) % 4) { |
|
62
|
|
|
case 0: |
|
63
|
|
|
break; |
|
64
|
|
|
case 2: |
|
65
|
|
|
$convertedData .= '=='; |
|
66
|
|
|
break; |
|
67
|
|
|
case 3: |
|
68
|
|
|
$convertedData .= '='; |
|
69
|
|
|
break; |
|
70
|
|
|
default: |
|
71
|
|
|
throw new InvalidArgumentException('invalid base64url string length'); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
return parent::decode($convertedData); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|