1 | <?php |
||
21 | abstract class PBES2AESKW implements KeyWrappingInterface |
||
22 | { |
||
23 | /** |
||
24 | * @var int |
||
25 | */ |
||
26 | private $salt_size; |
||
27 | |||
28 | /** |
||
29 | * @var int |
||
30 | */ |
||
31 | private $nb_count; |
||
32 | |||
33 | /** |
||
34 | * @param int $salt_size |
||
35 | * @param int $nb_count |
||
36 | */ |
||
37 | public function __construct($salt_size = 64, $nb_count = 4096) |
||
42 | |||
43 | /** |
||
44 | * {@inheritdoc} |
||
45 | */ |
||
46 | public function wrapKey(JWKInterface $key, $cek, array $complete_headers, array &$additional_headers) |
||
47 | { |
||
48 | $this->checkKey($key); |
||
49 | $this->checkHeaderAlgorithm($complete_headers); |
||
50 | $wrapper = $this->getWrapper(); |
||
51 | $hash_algorithm = $this->getHashAlgorithm(); |
||
52 | $key_size = $this->getKeySize(); |
||
53 | $salt = random_bytes($this->salt_size); |
||
54 | $password = Base64Url::decode($key->get('k')); |
||
55 | |||
56 | // We set headers parameters |
||
57 | $additional_headers['p2s'] = Base64Url::encode($salt); |
||
58 | $additional_headers['p2c'] = $this->nb_count; |
||
59 | |||
60 | $derived_key = hash_pbkdf2($hash_algorithm, $password, $complete_headers['alg']."\x00".$salt, $this->nb_count, $key_size, true); |
||
61 | |||
62 | return $wrapper->wrap($derived_key, $cek); |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * {@inheritdoc} |
||
67 | */ |
||
68 | public function unwrapKey(JWKInterface $key, $encrypted_cek, array $header) |
||
84 | |||
85 | /** |
||
86 | * {@inheritdoc} |
||
87 | */ |
||
88 | public function getKeyManagementMode() |
||
89 | { |
||
90 | return self::MODE_WRAP; |
||
91 | } |
||
92 | |||
93 | /** |
||
94 | * @param JWKInterface $key |
||
95 | */ |
||
96 | protected function checkKey(JWKInterface $key) |
||
97 | { |
||
98 | Assertion::eq($key->get('kty'), 'oct', 'Wrong key type.'); |
||
99 | Assertion::true($key->has('k'), 'The key parameter "k" is missing.'); |
||
100 | } |
||
101 | |||
102 | /** |
||
103 | * @param array $header |
||
104 | */ |
||
105 | protected function checkHeaderAlgorithm(array $header) |
||
110 | |||
111 | /** |
||
112 | * @param array $header |
||
113 | */ |
||
114 | protected function checkHeaderAdditionalParameters(array $header) |
||
121 | |||
122 | /** |
||
123 | * @return \AESKW\A128KW|\AESKW\A192KW|\AESKW\A256KW |
||
124 | */ |
||
125 | abstract protected function getWrapper(); |
||
126 | |||
127 | /** |
||
128 | * @return string |
||
129 | */ |
||
130 | abstract protected function getHashAlgorithm(); |
||
131 | |||
132 | /** |
||
133 | * @return int |
||
134 | */ |
||
135 | abstract protected function getKeySize(); |
||
136 | } |
||
137 |