|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Emarref\Jwt\Encryption; |
|
4
|
|
|
|
|
5
|
|
|
use Emarref\Jwt\Algorithm; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* @property Algorithm\AsymmetricInterface $algorithm |
|
9
|
|
|
*/ |
|
10
|
|
|
class Asymmetric extends AbstractEncryption implements EncryptionInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var string|resource |
|
14
|
|
|
*/ |
|
15
|
|
|
private $privateKey; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var string|resource |
|
19
|
|
|
*/ |
|
20
|
|
|
private $publicKey; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param Algorithm\AsymmetricInterface $algorithm |
|
24
|
|
|
*/ |
|
25
|
|
|
public function __construct(Algorithm\AsymmetricInterface $algorithm) |
|
26
|
|
|
{ |
|
27
|
|
|
parent::__construct($algorithm); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @return resource|string |
|
32
|
|
|
*/ |
|
33
|
|
|
public function getPrivateKey() |
|
34
|
|
|
{ |
|
35
|
|
|
if (!$this->privateKey) { |
|
36
|
|
|
throw new \RuntimeException('No private key available for encryption.'); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return $this->privateKey; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param resource|string $privateKey |
|
44
|
|
|
* @return $this |
|
45
|
|
|
*/ |
|
46
|
|
|
public function setPrivateKey($privateKey) |
|
47
|
|
|
{ |
|
48
|
|
|
$this->privateKey = $privateKey; |
|
49
|
|
|
return $this; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @return resource|string |
|
54
|
|
|
*/ |
|
55
|
|
|
public function getPublicKey() |
|
56
|
|
|
{ |
|
57
|
|
|
if (!$this->publicKey) { |
|
58
|
|
|
throw new \RuntimeException('No public key available for verification.'); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
return $this->publicKey; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @param resource|string $publicKey |
|
66
|
|
|
* @return $this |
|
67
|
|
|
*/ |
|
68
|
|
|
public function setPublicKey($publicKey) |
|
69
|
|
|
{ |
|
70
|
|
|
$this->publicKey = $publicKey; |
|
71
|
|
|
return $this; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
/** |
|
75
|
|
|
* @param string $value |
|
76
|
|
|
* @return string |
|
77
|
|
|
*/ |
|
78
|
|
|
public function encrypt($value) |
|
79
|
|
|
{ |
|
80
|
|
|
return $this->algorithm->sign($value, $this->getPrivateKey()); |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
/** |
|
84
|
|
|
* @param string $value |
|
85
|
|
|
* @param string $signature |
|
86
|
|
|
* @return boolean |
|
87
|
|
|
*/ |
|
88
|
|
|
public function verify($value, $signature) |
|
89
|
|
|
{ |
|
90
|
|
|
return $this->algorithm->verify($value, $signature, $this->getPublicKey()); |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|