1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the tmilos/jose-jwt package. |
5
|
|
|
* |
6
|
|
|
* (c) Milos Tomic <[email protected]> |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the MIT license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Tmilos\JoseJwt\Jwe; |
13
|
|
|
|
14
|
|
|
use Tmilos\JoseJwt\Error\JoseJwtException; |
15
|
|
|
use Tmilos\JoseJwt\Random\RandomGenerator; |
16
|
|
|
|
17
|
|
|
class RsaAlgorithm implements JweAlgorithm |
18
|
|
|
{ |
19
|
|
|
/** @var int */ |
20
|
|
|
private $padding; |
21
|
|
|
|
22
|
|
|
/** @var RandomGenerator */ |
23
|
|
|
private $randomGenerator; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param int $padding |
27
|
|
|
* @param RandomGenerator $randomGenerator |
28
|
|
|
*/ |
29
|
|
|
public function __construct($padding, RandomGenerator $randomGenerator) |
30
|
|
|
{ |
31
|
|
|
$this->padding = $padding; |
32
|
|
|
$this->randomGenerator = $randomGenerator; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param int $cekSizeBits |
37
|
|
|
* @param string|resource $kek |
38
|
|
|
* @param array $header |
39
|
|
|
* |
40
|
|
|
* @return array [cek, encryptedCek] |
41
|
|
|
*/ |
42
|
|
|
public function wrapNewKey($cekSizeBits, $kek, array $header) |
43
|
|
|
{ |
44
|
|
|
$cek = $this->randomGenerator->get($cekSizeBits / 8); |
45
|
|
|
if (false == openssl_public_encrypt($cek, $cekEncrypted, $kek, $this->padding)) { |
|
|
|
|
46
|
|
|
throw new JoseJwtException('Unable to encrypt CEK'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return [$cek, $cekEncrypted]; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param string $encryptedCek |
54
|
|
|
* @param string|resource $key |
55
|
|
|
* @param int $cekSizeBits |
56
|
|
|
* @param array $header |
57
|
|
|
* |
58
|
|
|
* @return string |
59
|
|
|
*/ |
60
|
|
|
public function unwrap($encryptedCek, $key, $cekSizeBits, array $header) |
61
|
|
|
{ |
62
|
|
|
if (false == openssl_private_decrypt($encryptedCek, $cek, $key, $this->padding)) { |
|
|
|
|
63
|
|
|
throw new JoseJwtException('Unable to decrypt CEK'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $cek; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
When comparing two booleans, it is generally considered safer to use the strict comparison operator.