-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBase64Trait.php
More file actions
59 lines (47 loc) · 1.96 KB
/
Base64Trait.php
File metadata and controls
59 lines (47 loc) · 1.96 KB
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
<?php
declare(strict_types=1);
namespace SimpleSAML\Assert;
use InvalidArgumentException;
use function base64_decode;
use function base64_encode;
use function filter_var;
use function sprintf;
/**
* @package simplesamlphp/assert
*/
trait Base64Trait
{
private static string $base64_regex = '/^(?:[a-z0-9+\/]{4})*(?:[a-z0-9+\/]{2}==|[a-z0-9+\/]{3}=)?$/i';
/***********************************************************************************
* NOTE: Custom assertions may be added below this line. *
* They SHOULD be marked as `protected` to ensure the call is forced *
* through __callStatic(). *
* Assertions marked `public` are called directly and will *
* not handle any custom exception passed to it. *
***********************************************************************************/
/**
* Note: This test is not bullet-proof but prevents a string containing illegal characters
* from being passed and ensures the string roughly follows the correct format for a Base64 encoded string
*/
protected static function validBase64(string $value, string $message = ''): string
{
$result = true;
if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$base64_regex]]) === false) {
$result = false;
} else {
$decoded = base64_decode($value, true);
if (empty($decoded)) { // Invalid _or_ empty string
$result = false;
} elseif (base64_encode($decoded) !== $value) {
$result = false;
}
}
if ($result === false) {
throw new InvalidArgumentException(sprintf(
$message ?: '\'%s\' is not a valid Base64 encoded string',
$value,
));
}
return $value;
}
}