|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Emarref\Jwt\Algorithm; |
|
4
|
|
|
|
|
5
|
|
|
abstract class RsaSsaPkcs implements AsymmetricInterface |
|
6
|
|
|
{ |
|
7
|
|
|
public function __construct() |
|
8
|
|
|
{ |
|
9
|
|
|
$this->ensureSupport(); |
|
10
|
|
|
} |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @throws \RuntimeException |
|
14
|
|
|
*/ |
|
15
|
|
|
public function ensureSupport() |
|
16
|
|
|
{ |
|
17
|
|
|
if (!function_exists('openssl_sign')) { |
|
18
|
|
|
throw new \RuntimeException('Openssl is required to use RSA encryption.'); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
$supportedAlgorithms = openssl_get_md_methods(true); |
|
22
|
|
|
|
|
23
|
|
|
if (!in_array($this->getAlgorithm(), $supportedAlgorithms)) { |
|
24
|
|
|
throw new \RuntimeException('Algorithm "%s" is not supported on this system.', $this->getAlgorithm()); |
|
25
|
|
|
} |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @return array |
|
30
|
|
|
*/ |
|
31
|
|
|
private function getSslErrors() |
|
32
|
|
|
{ |
|
33
|
|
|
$messages = []; |
|
34
|
|
|
|
|
35
|
|
|
while ($msg = openssl_error_string()) { |
|
36
|
|
|
$messages[] = $msg; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return $messages; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param string $value |
|
44
|
|
|
* @param string|resource $privateKey |
|
45
|
|
|
* @return string |
|
46
|
|
|
*/ |
|
47
|
|
View Code Duplication |
public function sign($value, $privateKey) |
|
48
|
|
|
{ |
|
49
|
|
|
$result = openssl_sign($value, $signature, $privateKey, $this->getAlgorithm()); |
|
50
|
|
|
|
|
51
|
|
|
if (false === $result) { |
|
52
|
|
|
throw new \RuntimeException('Failed to encrypt value. ' . implode("\n", $this->getSslErrors())); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return $signature; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @param string $value |
|
60
|
|
|
* @param string $signature |
|
61
|
|
|
* @param string|resource $publicKey |
|
62
|
|
|
* @return boolean |
|
63
|
|
|
*/ |
|
64
|
|
View Code Duplication |
public function verify($value, $signature, $publicKey) |
|
65
|
|
|
{ |
|
66
|
|
|
$result = openssl_verify($value, $signature, $publicKey, $this->getAlgorithm()); |
|
67
|
|
|
|
|
68
|
|
|
if ($result === -1) { |
|
69
|
|
|
throw new \RuntimeException('Failed to verify signature. ' . implode("\n", $this->getSslErrors())); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return (boolean)$result; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @return integer |
|
77
|
|
|
*/ |
|
78
|
|
|
abstract protected function getAlgorithm(); |
|
79
|
|
|
} |
|
80
|
|
|
|