GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Branch php72 (880eb0)
by Joni
05:58
created
lib/JWX/JWE/KeyManagementAlgorithm.php 1 patch
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -17,127 +17,127 @@
 block discarded – undo
17 17
  */
18 18
 abstract class KeyManagementAlgorithm implements AlgorithmParameterValue, HeaderParameters
19 19
 {
20
-    /**
21
-     * ID of the key used by the algorithm.
22
-     *
23
-     * If set, KeyID parameter shall be automatically inserted into JWE's
24
-     * header.
25
-     *
26
-     * @var null|string
27
-     */
28
-    protected $_keyID;
20
+	/**
21
+	 * ID of the key used by the algorithm.
22
+	 *
23
+	 * If set, KeyID parameter shall be automatically inserted into JWE's
24
+	 * header.
25
+	 *
26
+	 * @var null|string
27
+	 */
28
+	protected $_keyID;
29 29
 
30
-    /**
31
-     * Encrypt a key to be inserted into JWE header.
32
-     *
33
-     * @param string      $cek    Content encryption key
34
-     * @param null|Header $header Optional reference to the Header variable,
35
-     *                            which may be updated to contain parameters
36
-     *                            specific to this encrypt invocation.
37
-     *                            If the variable is referenced, but is a null,
38
-     *                            it shall be initialized to an empty Header.
39
-     *
40
-     * @throws \RuntimeException For generic errors
41
-     *
42
-     * @return string Encrypted key
43
-     */
44
-    final public function encrypt(string $cek, Header &$header = null): string
45
-    {
46
-        if (!isset($header)) {
47
-            $header = new Header();
48
-        }
49
-        return $this->_encryptKey($cek, $header);
50
-    }
30
+	/**
31
+	 * Encrypt a key to be inserted into JWE header.
32
+	 *
33
+	 * @param string      $cek    Content encryption key
34
+	 * @param null|Header $header Optional reference to the Header variable,
35
+	 *                            which may be updated to contain parameters
36
+	 *                            specific to this encrypt invocation.
37
+	 *                            If the variable is referenced, but is a null,
38
+	 *                            it shall be initialized to an empty Header.
39
+	 *
40
+	 * @throws \RuntimeException For generic errors
41
+	 *
42
+	 * @return string Encrypted key
43
+	 */
44
+	final public function encrypt(string $cek, Header &$header = null): string
45
+	{
46
+		if (!isset($header)) {
47
+			$header = new Header();
48
+		}
49
+		return $this->_encryptKey($cek, $header);
50
+	}
51 51
 
52
-    /**
53
-     * Decrypt a CEK from the encrypted data.
54
-     *
55
-     * @param string      $data   Encrypted key
56
-     * @param null|Header $header Optional header containing parameters
57
-     *                            required to decrypt the key
58
-     *
59
-     * @throws \RuntimeException For generic errors
60
-     *
61
-     * @return string Content encryption key
62
-     */
63
-    final public function decrypt(string $data, ?Header $header = null): string
64
-    {
65
-        if (!isset($header)) {
66
-            $header = new Header();
67
-        }
68
-        return $this->_decryptKey($data, $header);
69
-    }
52
+	/**
53
+	 * Decrypt a CEK from the encrypted data.
54
+	 *
55
+	 * @param string      $data   Encrypted key
56
+	 * @param null|Header $header Optional header containing parameters
57
+	 *                            required to decrypt the key
58
+	 *
59
+	 * @throws \RuntimeException For generic errors
60
+	 *
61
+	 * @return string Content encryption key
62
+	 */
63
+	final public function decrypt(string $data, ?Header $header = null): string
64
+	{
65
+		if (!isset($header)) {
66
+			$header = new Header();
67
+		}
68
+		return $this->_decryptKey($data, $header);
69
+	}
70 70
 
71
-    /**
72
-     * Get content encryption key for the encryption.
73
-     *
74
-     * Returned key may be random depending on the key management algorithm.
75
-     *
76
-     * @param int $length Required key size in bytes
77
-     *
78
-     * @return string
79
-     */
80
-    abstract public function cekForEncryption(int $length): string;
71
+	/**
72
+	 * Get content encryption key for the encryption.
73
+	 *
74
+	 * Returned key may be random depending on the key management algorithm.
75
+	 *
76
+	 * @param int $length Required key size in bytes
77
+	 *
78
+	 * @return string
79
+	 */
80
+	abstract public function cekForEncryption(int $length): string;
81 81
 
82
-    /**
83
-     * Initialize key management algorithm from a JWK and a header.
84
-     *
85
-     * @param JWK    $jwk
86
-     * @param Header $header
87
-     *
88
-     * @return KeyManagementAlgorithm
89
-     */
90
-    public static function fromJWK(JWK $jwk, Header $header): KeyManagementAlgorithm
91
-    {
92
-        $factory = new KeyAlgorithmFactory($header);
93
-        return $factory->algoByKey($jwk);
94
-    }
82
+	/**
83
+	 * Initialize key management algorithm from a JWK and a header.
84
+	 *
85
+	 * @param JWK    $jwk
86
+	 * @param Header $header
87
+	 *
88
+	 * @return KeyManagementAlgorithm
89
+	 */
90
+	public static function fromJWK(JWK $jwk, Header $header): KeyManagementAlgorithm
91
+	{
92
+		$factory = new KeyAlgorithmFactory($header);
93
+		return $factory->algoByKey($jwk);
94
+	}
95 95
 
96
-    /**
97
-     * Get self with key ID.
98
-     *
99
-     * @param null|string $id Key ID or null to remove
100
-     *
101
-     * @return self
102
-     */
103
-    public function withKeyID(?string $id): self
104
-    {
105
-        $obj = clone $this;
106
-        $obj->_keyID = $id;
107
-        return $obj;
108
-    }
96
+	/**
97
+	 * Get self with key ID.
98
+	 *
99
+	 * @param null|string $id Key ID or null to remove
100
+	 *
101
+	 * @return self
102
+	 */
103
+	public function withKeyID(?string $id): self
104
+	{
105
+		$obj = clone $this;
106
+		$obj->_keyID = $id;
107
+		return $obj;
108
+	}
109 109
 
110
-    /**
111
-     * {@inheritdoc}
112
-     */
113
-    public function headerParameters(): array
114
-    {
115
-        $params = [];
116
-        if (isset($this->_keyID)) {
117
-            $params[] = new KeyIDParameter($this->_keyID);
118
-        }
119
-        return $params;
120
-    }
110
+	/**
111
+	 * {@inheritdoc}
112
+	 */
113
+	public function headerParameters(): array
114
+	{
115
+		$params = [];
116
+		if (isset($this->_keyID)) {
117
+			$params[] = new KeyIDParameter($this->_keyID);
118
+		}
119
+		return $params;
120
+	}
121 121
 
122
-    /**
123
-     * Encrypt a key.
124
-     *
125
-     * @param string $key    Key to be encrypted
126
-     * @param Header $header Reference to the Header variable, that shall
127
-     *                       be updated to contain parameters specific to the encryption
128
-     *
129
-     * @return string Ciphertext
130
-     */
131
-    abstract protected function _encryptKey(string $key, Header &$header): string;
122
+	/**
123
+	 * Encrypt a key.
124
+	 *
125
+	 * @param string $key    Key to be encrypted
126
+	 * @param Header $header Reference to the Header variable, that shall
127
+	 *                       be updated to contain parameters specific to the encryption
128
+	 *
129
+	 * @return string Ciphertext
130
+	 */
131
+	abstract protected function _encryptKey(string $key, Header &$header): string;
132 132
 
133
-    /**
134
-     * Decrypt a key.
135
-     *
136
-     * @param string $ciphertext Ciphertext of the encrypted key
137
-     * @param Header $header     Header possibly containing encoding specific
138
-     *                           parameters
139
-     *
140
-     * @return string Plaintext key
141
-     */
142
-    abstract protected function _decryptKey(string $ciphertext, Header $header): string;
133
+	/**
134
+	 * Decrypt a key.
135
+	 *
136
+	 * @param string $ciphertext Ciphertext of the encrypted key
137
+	 * @param Header $header     Header possibly containing encoding specific
138
+	 *                           parameters
139
+	 *
140
+	 * @return string Plaintext key
141
+	 */
142
+	abstract protected function _decryptKey(string $ciphertext, Header $header): string;
143 143
 }
Please login to merge, or discard this patch.
lib/JWX/JWE/ContentEncryptionAlgorithm.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -12,44 +12,44 @@
 block discarded – undo
12 12
  */
13 13
 interface ContentEncryptionAlgorithm extends EncryptionAlgorithmParameterValue, HeaderParameters
14 14
 {
15
-    /**
16
-     * Encrypt plaintext.
17
-     *
18
-     * @param string $plaintext Data to encrypt
19
-     * @param string $key       Encryption key
20
-     * @param string $iv        Initialization vector
21
-     * @param string $aad       Additional authenticated data
22
-     *
23
-     * @return array Tuple of ciphertext and authentication tag
24
-     */
25
-    public function encrypt(string $plaintext, string $key, string $iv,
26
-        string $aad): array;
15
+	/**
16
+	 * Encrypt plaintext.
17
+	 *
18
+	 * @param string $plaintext Data to encrypt
19
+	 * @param string $key       Encryption key
20
+	 * @param string $iv        Initialization vector
21
+	 * @param string $aad       Additional authenticated data
22
+	 *
23
+	 * @return array Tuple of ciphertext and authentication tag
24
+	 */
25
+	public function encrypt(string $plaintext, string $key, string $iv,
26
+		string $aad): array;
27 27
 
28
-    /**
29
-     * Decrypt ciphertext.
30
-     *
31
-     * @param string $ciphertext Data to decrypt
32
-     * @param string $key        Encryption key
33
-     * @param string $iv         Initialization vector
34
-     * @param string $aad        Additional authenticated data
35
-     * @param string $auth_tag   Authentication tag to compare
36
-     *
37
-     * @return string Plaintext
38
-     */
39
-    public function decrypt(string $ciphertext, string $key, string $iv,
40
-        string $aad, string $auth_tag): string;
28
+	/**
29
+	 * Decrypt ciphertext.
30
+	 *
31
+	 * @param string $ciphertext Data to decrypt
32
+	 * @param string $key        Encryption key
33
+	 * @param string $iv         Initialization vector
34
+	 * @param string $aad        Additional authenticated data
35
+	 * @param string $auth_tag   Authentication tag to compare
36
+	 *
37
+	 * @return string Plaintext
38
+	 */
39
+	public function decrypt(string $ciphertext, string $key, string $iv,
40
+		string $aad, string $auth_tag): string;
41 41
 
42
-    /**
43
-     * Get the required key size in bytes.
44
-     *
45
-     * @return int
46
-     */
47
-    public function keySize(): int;
42
+	/**
43
+	 * Get the required key size in bytes.
44
+	 *
45
+	 * @return int
46
+	 */
47
+	public function keySize(): int;
48 48
 
49
-    /**
50
-     * Get the required IV size in bytes.
51
-     *
52
-     * @return int
53
-     */
54
-    public function ivSize(): int;
49
+	/**
50
+	 * Get the required IV size in bytes.
51
+	 *
52
+	 * @return int
53
+	 */
54
+	public function ivSize(): int;
55 55
 }
Please login to merge, or discard this patch.
lib/JWX/JWE/KeyAlgorithm/PBES2Algorithm.php 1 patch
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -22,199 +22,199 @@
 block discarded – undo
22 22
  */
23 23
 abstract class PBES2Algorithm extends KeyManagementAlgorithm
24 24
 {
25
-    use RandomCEK;
26
-
27
-    /**
28
-     * Mapping from algorithm name to class name.
29
-     *
30
-     * @internal
31
-     *
32
-     * @var array
33
-     */
34
-    const MAP_ALGO_TO_CLASS = [
35
-        JWA::ALGO_PBES2_HS256_A128KW => PBES2HS256A128KWAlgorithm::class,
36
-        JWA::ALGO_PBES2_HS384_A192KW => PBES2HS384A192KWAlgorithm::class,
37
-        JWA::ALGO_PBES2_HS512_A256KW => PBES2HS512A256KWAlgorithm::class,
38
-    ];
39
-
40
-    /**
41
-     * Password.
42
-     *
43
-     * @var string
44
-     */
45
-    protected $_password;
46
-
47
-    /**
48
-     * Salt input.
49
-     *
50
-     * @var string
51
-     */
52
-    protected $_saltInput;
53
-
54
-    /**
55
-     * Iteration count.
56
-     *
57
-     * @var int
58
-     */
59
-    protected $_count;
60
-
61
-    /**
62
-     * Derived key.
63
-     *
64
-     * @var string
65
-     */
66
-    private $_derivedKey;
67
-
68
-    /**
69
-     * Constructor.
70
-     *
71
-     * @param string $password   Password
72
-     * @param string $salt_input Salt input
73
-     * @param int    $count      Iteration count
74
-     */
75
-    public function __construct(string $password, string $salt_input, int $count)
76
-    {
77
-        $this->_password = $password;
78
-        $this->_saltInput = $salt_input;
79
-        $this->_count = $count;
80
-    }
81
-
82
-    /**
83
-     * Initialize from JWK.
84
-     *
85
-     * @param JWK    $jwk
86
-     * @param Header $header
87
-     *
88
-     * @throws \UnexpectedValueException
89
-     *
90
-     * @return self
91
-     */
92
-    public static function fromJWK(JWK $jwk, Header $header): KeyManagementAlgorithm
93
-    {
94
-        $jwk = SymmetricKeyJWK::fromJWK($jwk);
95
-        if (!$header->hasPBES2SaltInput()) {
96
-            throw new \UnexpectedValueException('No salt input.');
97
-        }
98
-        $salt_input = $header->PBES2SaltInput()->saltInput();
99
-        if (!$header->hasPBES2Count()) {
100
-            throw new \UnexpectedValueException('No iteration count.');
101
-        }
102
-        $count = $header->PBES2Count()->value();
103
-        $alg = JWA::deriveAlgorithmName($header, $jwk);
104
-        if (!array_key_exists($alg, self::MAP_ALGO_TO_CLASS)) {
105
-            throw new \UnexpectedValueException("Unsupported algorithm '{$alg}'.");
106
-        }
107
-        $cls = self::MAP_ALGO_TO_CLASS[$alg];
108
-        return new $cls($jwk->key(), $salt_input, $count);
109
-    }
110
-
111
-    /**
112
-     * Initialize from a password with random salt and default iteration count.
113
-     *
114
-     * @param string $password   Password
115
-     * @param int    $count      Optional user defined iteration count
116
-     * @param int    $salt_bytes Optional user defined salt length
117
-     *
118
-     * @return self
119
-     */
120
-    public static function fromPassword(string $password, int $count = 64000,
121
-        int $salt_bytes = 8): self
122
-    {
123
-        $salt_input = openssl_random_pseudo_bytes($salt_bytes);
124
-        return new static($password, $salt_input, $count);
125
-    }
126
-
127
-    /**
128
-     * Get salt input.
129
-     *
130
-     * @return string
131
-     */
132
-    public function saltInput(): string
133
-    {
134
-        return $this->_saltInput;
135
-    }
136
-
137
-    /**
138
-     * Get computed salt.
139
-     *
140
-     * @return string
141
-     */
142
-    public function salt(): string
143
-    {
144
-        return PBES2SaltInputParameter::fromString($this->_saltInput)->salt(
145
-            AlgorithmParameter::fromAlgorithm($this));
146
-    }
147
-
148
-    /**
149
-     * Get iteration count.
150
-     *
151
-     * @return int
152
-     */
153
-    public function iterationCount(): int
154
-    {
155
-        return $this->_count;
156
-    }
157
-
158
-    /**
159
-     * {@inheritdoc}
160
-     */
161
-    public function headerParameters(): array
162
-    {
163
-        return array_merge(parent::headerParameters(),
164
-            [AlgorithmParameter::fromAlgorithm($this),
165
-                PBES2SaltInputParameter::fromString($this->_saltInput),
166
-                new PBES2CountParameter($this->_count), ]);
167
-    }
168
-
169
-    /**
170
-     * Get hash algorithm for hash_pbkdf2.
171
-     *
172
-     * @return string
173
-     */
174
-    abstract protected function _hashAlgo(): string;
175
-
176
-    /**
177
-     * Get derived key length.
178
-     *
179
-     * @return int
180
-     */
181
-    abstract protected function _keyLength(): int;
182
-
183
-    /**
184
-     * Get key wrapping algoritym.
185
-     *
186
-     * @return AESKeyWrapAlgorithm
187
-     */
188
-    abstract protected function _kwAlgo(): AESKeyWrapAlgorithm;
189
-
190
-    /**
191
-     * Get derived key.
192
-     *
193
-     * @return string
194
-     */
195
-    protected function _derivedKey(): string
196
-    {
197
-        if (!isset($this->_derivedKey)) {
198
-            $this->_derivedKey = hash_pbkdf2($this->_hashAlgo(),
199
-                $this->_password, $this->salt(), $this->_count,
200
-                $this->_keyLength(), true);
201
-        }
202
-        return $this->_derivedKey;
203
-    }
204
-
205
-    /**
206
-     * {@inheritdoc}
207
-     */
208
-    protected function _encryptKey(string $key, Header &$header): string
209
-    {
210
-        return $this->_kwAlgo()->wrap($key, $this->_derivedKey());
211
-    }
212
-
213
-    /**
214
-     * {@inheritdoc}
215
-     */
216
-    protected function _decryptKey(string $ciphertext, Header $header): string
217
-    {
218
-        return $this->_kwAlgo()->unwrap($ciphertext, $this->_derivedKey());
219
-    }
25
+	use RandomCEK;
26
+
27
+	/**
28
+	 * Mapping from algorithm name to class name.
29
+	 *
30
+	 * @internal
31
+	 *
32
+	 * @var array
33
+	 */
34
+	const MAP_ALGO_TO_CLASS = [
35
+		JWA::ALGO_PBES2_HS256_A128KW => PBES2HS256A128KWAlgorithm::class,
36
+		JWA::ALGO_PBES2_HS384_A192KW => PBES2HS384A192KWAlgorithm::class,
37
+		JWA::ALGO_PBES2_HS512_A256KW => PBES2HS512A256KWAlgorithm::class,
38
+	];
39
+
40
+	/**
41
+	 * Password.
42
+	 *
43
+	 * @var string
44
+	 */
45
+	protected $_password;
46
+
47
+	/**
48
+	 * Salt input.
49
+	 *
50
+	 * @var string
51
+	 */
52
+	protected $_saltInput;
53
+
54
+	/**
55
+	 * Iteration count.
56
+	 *
57
+	 * @var int
58
+	 */
59
+	protected $_count;
60
+
61
+	/**
62
+	 * Derived key.
63
+	 *
64
+	 * @var string
65
+	 */
66
+	private $_derivedKey;
67
+
68
+	/**
69
+	 * Constructor.
70
+	 *
71
+	 * @param string $password   Password
72
+	 * @param string $salt_input Salt input
73
+	 * @param int    $count      Iteration count
74
+	 */
75
+	public function __construct(string $password, string $salt_input, int $count)
76
+	{
77
+		$this->_password = $password;
78
+		$this->_saltInput = $salt_input;
79
+		$this->_count = $count;
80
+	}
81
+
82
+	/**
83
+	 * Initialize from JWK.
84
+	 *
85
+	 * @param JWK    $jwk
86
+	 * @param Header $header
87
+	 *
88
+	 * @throws \UnexpectedValueException
89
+	 *
90
+	 * @return self
91
+	 */
92
+	public static function fromJWK(JWK $jwk, Header $header): KeyManagementAlgorithm
93
+	{
94
+		$jwk = SymmetricKeyJWK::fromJWK($jwk);
95
+		if (!$header->hasPBES2SaltInput()) {
96
+			throw new \UnexpectedValueException('No salt input.');
97
+		}
98
+		$salt_input = $header->PBES2SaltInput()->saltInput();
99
+		if (!$header->hasPBES2Count()) {
100
+			throw new \UnexpectedValueException('No iteration count.');
101
+		}
102
+		$count = $header->PBES2Count()->value();
103
+		$alg = JWA::deriveAlgorithmName($header, $jwk);
104
+		if (!array_key_exists($alg, self::MAP_ALGO_TO_CLASS)) {
105
+			throw new \UnexpectedValueException("Unsupported algorithm '{$alg}'.");
106
+		}
107
+		$cls = self::MAP_ALGO_TO_CLASS[$alg];
108
+		return new $cls($jwk->key(), $salt_input, $count);
109
+	}
110
+
111
+	/**
112
+	 * Initialize from a password with random salt and default iteration count.
113
+	 *
114
+	 * @param string $password   Password
115
+	 * @param int    $count      Optional user defined iteration count
116
+	 * @param int    $salt_bytes Optional user defined salt length
117
+	 *
118
+	 * @return self
119
+	 */
120
+	public static function fromPassword(string $password, int $count = 64000,
121
+		int $salt_bytes = 8): self
122
+	{
123
+		$salt_input = openssl_random_pseudo_bytes($salt_bytes);
124
+		return new static($password, $salt_input, $count);
125
+	}
126
+
127
+	/**
128
+	 * Get salt input.
129
+	 *
130
+	 * @return string
131
+	 */
132
+	public function saltInput(): string
133
+	{
134
+		return $this->_saltInput;
135
+	}
136
+
137
+	/**
138
+	 * Get computed salt.
139
+	 *
140
+	 * @return string
141
+	 */
142
+	public function salt(): string
143
+	{
144
+		return PBES2SaltInputParameter::fromString($this->_saltInput)->salt(
145
+			AlgorithmParameter::fromAlgorithm($this));
146
+	}
147
+
148
+	/**
149
+	 * Get iteration count.
150
+	 *
151
+	 * @return int
152
+	 */
153
+	public function iterationCount(): int
154
+	{
155
+		return $this->_count;
156
+	}
157
+
158
+	/**
159
+	 * {@inheritdoc}
160
+	 */
161
+	public function headerParameters(): array
162
+	{
163
+		return array_merge(parent::headerParameters(),
164
+			[AlgorithmParameter::fromAlgorithm($this),
165
+				PBES2SaltInputParameter::fromString($this->_saltInput),
166
+				new PBES2CountParameter($this->_count), ]);
167
+	}
168
+
169
+	/**
170
+	 * Get hash algorithm for hash_pbkdf2.
171
+	 *
172
+	 * @return string
173
+	 */
174
+	abstract protected function _hashAlgo(): string;
175
+
176
+	/**
177
+	 * Get derived key length.
178
+	 *
179
+	 * @return int
180
+	 */
181
+	abstract protected function _keyLength(): int;
182
+
183
+	/**
184
+	 * Get key wrapping algoritym.
185
+	 *
186
+	 * @return AESKeyWrapAlgorithm
187
+	 */
188
+	abstract protected function _kwAlgo(): AESKeyWrapAlgorithm;
189
+
190
+	/**
191
+	 * Get derived key.
192
+	 *
193
+	 * @return string
194
+	 */
195
+	protected function _derivedKey(): string
196
+	{
197
+		if (!isset($this->_derivedKey)) {
198
+			$this->_derivedKey = hash_pbkdf2($this->_hashAlgo(),
199
+				$this->_password, $this->salt(), $this->_count,
200
+				$this->_keyLength(), true);
201
+		}
202
+		return $this->_derivedKey;
203
+	}
204
+
205
+	/**
206
+	 * {@inheritdoc}
207
+	 */
208
+	protected function _encryptKey(string $key, Header &$header): string
209
+	{
210
+		return $this->_kwAlgo()->wrap($key, $this->_derivedKey());
211
+	}
212
+
213
+	/**
214
+	 * {@inheritdoc}
215
+	 */
216
+	protected function _decryptKey(string $ciphertext, Header $header): string
217
+	{
218
+		return $this->_kwAlgo()->unwrap($ciphertext, $this->_derivedKey());
219
+	}
220 220
 }
Please login to merge, or discard this patch.
lib/JWX/JWE/KeyAlgorithm/RSAESKeyAlgorithm.php 1 patch
Indentation   +198 added lines, -198 removed lines patch added patch discarded remove patch
@@ -21,202 +21,202 @@
 block discarded – undo
21 21
  */
22 22
 abstract class RSAESKeyAlgorithm extends KeyManagementAlgorithm
23 23
 {
24
-    use RandomCEK;
25
-
26
-    /**
27
-     * Mapping from algorithm name to class name.
28
-     *
29
-     * @internal
30
-     *
31
-     * @var array
32
-     */
33
-    const MAP_ALGO_TO_CLASS = [
34
-        JWA::ALGO_RSA1_5 => RSAESPKCS1Algorithm::class,
35
-        JWA::ALGO_RSA_OAEP => RSAESOAEPAlgorithm::class,
36
-    ];
37
-
38
-    /**
39
-     * Public key.
40
-     *
41
-     * @var RSAPublicKeyJWK
42
-     */
43
-    protected $_publicKey;
44
-
45
-    /**
46
-     * Private key.
47
-     *
48
-     * @var null|RSAPrivateKeyJWK
49
-     */
50
-    protected $_privateKey;
51
-
52
-    /**
53
-     * Constructor.
54
-     *
55
-     * Use <code>fromPublicKey</code> or <code>fromPrivateKey</code> instead!
56
-     *
57
-     * @param RSAPublicKeyJWK  $pub_key  RSA public key
58
-     * @param RSAPrivateKeyJWK $priv_key Optional RSA private key
59
-     */
60
-    protected function __construct(RSAPublicKeyJWK $pub_key,
61
-        ?RSAPrivateKeyJWK $priv_key = null)
62
-    {
63
-        $this->_publicKey = $pub_key;
64
-        $this->_privateKey = $priv_key;
65
-    }
66
-
67
-    /**
68
-     * Initialize from JWK.
69
-     *
70
-     * @param JWK    $jwk
71
-     * @param Header $header
72
-     *
73
-     * @throws \UnexpectedValueException
74
-     *
75
-     * @return self
76
-     */
77
-    public static function fromJWK(JWK $jwk, Header $header): KeyManagementAlgorithm
78
-    {
79
-        $alg = JWA::deriveAlgorithmName($header, $jwk);
80
-        if (!array_key_exists($alg, self::MAP_ALGO_TO_CLASS)) {
81
-            throw new \UnexpectedValueException("Unsupported algorithm '{$alg}'.");
82
-        }
83
-        $cls = self::MAP_ALGO_TO_CLASS[$alg];
84
-        if ($jwk->has(...RSAPrivateKeyJWK::MANAGED_PARAMS)) {
85
-            return $cls::fromPrivateKey(RSAPrivateKeyJWK::fromJWK($jwk));
86
-        }
87
-        return $cls::fromPublicKey(RSAPublicKeyJWK::fromJWK($jwk));
88
-    }
89
-
90
-    /**
91
-     * Initialize from a public key.
92
-     *
93
-     * @param RSAPublicKeyJWK $jwk
94
-     *
95
-     * @return self
96
-     */
97
-    public static function fromPublicKey(RSAPublicKeyJWK $jwk): self
98
-    {
99
-        return new static($jwk);
100
-    }
101
-
102
-    /**
103
-     * Initialize from a private key.
104
-     *
105
-     * @param RSAPrivateKeyJWK $jwk
106
-     *
107
-     * @return self
108
-     */
109
-    public static function fromPrivateKey(RSAPrivateKeyJWK $jwk): self
110
-    {
111
-        return new static($jwk->publicKey(), $jwk);
112
-    }
113
-
114
-    /**
115
-     * Get the public key.
116
-     *
117
-     * @return RSAPublicKeyJWK
118
-     */
119
-    public function publicKey(): RSAPublicKeyJWK
120
-    {
121
-        return $this->_publicKey;
122
-    }
123
-
124
-    /**
125
-     * Check whether the private key is present.
126
-     *
127
-     * @return bool
128
-     */
129
-    public function hasPrivateKey(): bool
130
-    {
131
-        return isset($this->_privateKey);
132
-    }
133
-
134
-    /**
135
-     * Get the private key.
136
-     *
137
-     * @throws \LogicException
138
-     *
139
-     * @return RSAPrivateKeyJWK
140
-     */
141
-    public function privateKey(): RSAPrivateKeyJWK
142
-    {
143
-        if (!$this->hasPrivateKey()) {
144
-            throw new \LogicException('Private key not set.');
145
-        }
146
-        return $this->_privateKey;
147
-    }
148
-
149
-    /**
150
-     * {@inheritdoc}
151
-     */
152
-    public function headerParameters(): array
153
-    {
154
-        return array_merge(parent::headerParameters(),
155
-            [AlgorithmParameter::fromAlgorithm($this)]);
156
-    }
157
-
158
-    /**
159
-     * Get the padding scheme.
160
-     *
161
-     * @return int
162
-     */
163
-    abstract protected function _paddingScheme(): int;
164
-
165
-    /**
166
-     * {@inheritdoc}
167
-     */
168
-    protected function _encryptKey(string $key, Header &$header): string
169
-    {
170
-        $pubkey = openssl_pkey_get_public(
171
-            $this->publicKey()->toPEM()->string());
172
-        if (false === $pubkey) {
173
-            throw new \RuntimeException(
174
-                'openssl_pkey_get_public() failed: ' .
175
-                     $this->_getLastOpenSSLError());
176
-        }
177
-        $result = openssl_public_encrypt($key, $crypted, $pubkey,
178
-            $this->_paddingScheme());
179
-        if (!$result) {
180
-            throw new \RuntimeException(
181
-                'openssl_public_encrypt() failed: ' .
182
-                     $this->_getLastOpenSSLError());
183
-        }
184
-        return $crypted;
185
-    }
186
-
187
-    /**
188
-     * {@inheritdoc}
189
-     */
190
-    protected function _decryptKey(string $ciphertext, Header $header): string
191
-    {
192
-        $privkey = openssl_pkey_get_private(
193
-            $this->privateKey()->toPEM()->string());
194
-        if (false === $privkey) {
195
-            throw new \RuntimeException(
196
-                'openssl_pkey_get_private() failed: ' .
197
-                     $this->_getLastOpenSSLError());
198
-        }
199
-        $result = openssl_private_decrypt($ciphertext, $cek, $privkey,
200
-            $this->_paddingScheme());
201
-        if (!$result) {
202
-            throw new \RuntimeException(
203
-                'openssl_private_decrypt() failed: ' .
204
-                     $this->_getLastOpenSSLError());
205
-        }
206
-        return $cek;
207
-    }
208
-
209
-    /**
210
-     * Get last OpenSSL error message.
211
-     *
212
-     * @return null|string
213
-     */
214
-    protected function _getLastOpenSSLError(): ?string
215
-    {
216
-        $msg = null;
217
-        while (false !== ($err = openssl_error_string())) {
218
-            $msg = $err;
219
-        }
220
-        return $msg;
221
-    }
24
+	use RandomCEK;
25
+
26
+	/**
27
+	 * Mapping from algorithm name to class name.
28
+	 *
29
+	 * @internal
30
+	 *
31
+	 * @var array
32
+	 */
33
+	const MAP_ALGO_TO_CLASS = [
34
+		JWA::ALGO_RSA1_5 => RSAESPKCS1Algorithm::class,
35
+		JWA::ALGO_RSA_OAEP => RSAESOAEPAlgorithm::class,
36
+	];
37
+
38
+	/**
39
+	 * Public key.
40
+	 *
41
+	 * @var RSAPublicKeyJWK
42
+	 */
43
+	protected $_publicKey;
44
+
45
+	/**
46
+	 * Private key.
47
+	 *
48
+	 * @var null|RSAPrivateKeyJWK
49
+	 */
50
+	protected $_privateKey;
51
+
52
+	/**
53
+	 * Constructor.
54
+	 *
55
+	 * Use <code>fromPublicKey</code> or <code>fromPrivateKey</code> instead!
56
+	 *
57
+	 * @param RSAPublicKeyJWK  $pub_key  RSA public key
58
+	 * @param RSAPrivateKeyJWK $priv_key Optional RSA private key
59
+	 */
60
+	protected function __construct(RSAPublicKeyJWK $pub_key,
61
+		?RSAPrivateKeyJWK $priv_key = null)
62
+	{
63
+		$this->_publicKey = $pub_key;
64
+		$this->_privateKey = $priv_key;
65
+	}
66
+
67
+	/**
68
+	 * Initialize from JWK.
69
+	 *
70
+	 * @param JWK    $jwk
71
+	 * @param Header $header
72
+	 *
73
+	 * @throws \UnexpectedValueException
74
+	 *
75
+	 * @return self
76
+	 */
77
+	public static function fromJWK(JWK $jwk, Header $header): KeyManagementAlgorithm
78
+	{
79
+		$alg = JWA::deriveAlgorithmName($header, $jwk);
80
+		if (!array_key_exists($alg, self::MAP_ALGO_TO_CLASS)) {
81
+			throw new \UnexpectedValueException("Unsupported algorithm '{$alg}'.");
82
+		}
83
+		$cls = self::MAP_ALGO_TO_CLASS[$alg];
84
+		if ($jwk->has(...RSAPrivateKeyJWK::MANAGED_PARAMS)) {
85
+			return $cls::fromPrivateKey(RSAPrivateKeyJWK::fromJWK($jwk));
86
+		}
87
+		return $cls::fromPublicKey(RSAPublicKeyJWK::fromJWK($jwk));
88
+	}
89
+
90
+	/**
91
+	 * Initialize from a public key.
92
+	 *
93
+	 * @param RSAPublicKeyJWK $jwk
94
+	 *
95
+	 * @return self
96
+	 */
97
+	public static function fromPublicKey(RSAPublicKeyJWK $jwk): self
98
+	{
99
+		return new static($jwk);
100
+	}
101
+
102
+	/**
103
+	 * Initialize from a private key.
104
+	 *
105
+	 * @param RSAPrivateKeyJWK $jwk
106
+	 *
107
+	 * @return self
108
+	 */
109
+	public static function fromPrivateKey(RSAPrivateKeyJWK $jwk): self
110
+	{
111
+		return new static($jwk->publicKey(), $jwk);
112
+	}
113
+
114
+	/**
115
+	 * Get the public key.
116
+	 *
117
+	 * @return RSAPublicKeyJWK
118
+	 */
119
+	public function publicKey(): RSAPublicKeyJWK
120
+	{
121
+		return $this->_publicKey;
122
+	}
123
+
124
+	/**
125
+	 * Check whether the private key is present.
126
+	 *
127
+	 * @return bool
128
+	 */
129
+	public function hasPrivateKey(): bool
130
+	{
131
+		return isset($this->_privateKey);
132
+	}
133
+
134
+	/**
135
+	 * Get the private key.
136
+	 *
137
+	 * @throws \LogicException
138
+	 *
139
+	 * @return RSAPrivateKeyJWK
140
+	 */
141
+	public function privateKey(): RSAPrivateKeyJWK
142
+	{
143
+		if (!$this->hasPrivateKey()) {
144
+			throw new \LogicException('Private key not set.');
145
+		}
146
+		return $this->_privateKey;
147
+	}
148
+
149
+	/**
150
+	 * {@inheritdoc}
151
+	 */
152
+	public function headerParameters(): array
153
+	{
154
+		return array_merge(parent::headerParameters(),
155
+			[AlgorithmParameter::fromAlgorithm($this)]);
156
+	}
157
+
158
+	/**
159
+	 * Get the padding scheme.
160
+	 *
161
+	 * @return int
162
+	 */
163
+	abstract protected function _paddingScheme(): int;
164
+
165
+	/**
166
+	 * {@inheritdoc}
167
+	 */
168
+	protected function _encryptKey(string $key, Header &$header): string
169
+	{
170
+		$pubkey = openssl_pkey_get_public(
171
+			$this->publicKey()->toPEM()->string());
172
+		if (false === $pubkey) {
173
+			throw new \RuntimeException(
174
+				'openssl_pkey_get_public() failed: ' .
175
+					 $this->_getLastOpenSSLError());
176
+		}
177
+		$result = openssl_public_encrypt($key, $crypted, $pubkey,
178
+			$this->_paddingScheme());
179
+		if (!$result) {
180
+			throw new \RuntimeException(
181
+				'openssl_public_encrypt() failed: ' .
182
+					 $this->_getLastOpenSSLError());
183
+		}
184
+		return $crypted;
185
+	}
186
+
187
+	/**
188
+	 * {@inheritdoc}
189
+	 */
190
+	protected function _decryptKey(string $ciphertext, Header $header): string
191
+	{
192
+		$privkey = openssl_pkey_get_private(
193
+			$this->privateKey()->toPEM()->string());
194
+		if (false === $privkey) {
195
+			throw new \RuntimeException(
196
+				'openssl_pkey_get_private() failed: ' .
197
+					 $this->_getLastOpenSSLError());
198
+		}
199
+		$result = openssl_private_decrypt($ciphertext, $cek, $privkey,
200
+			$this->_paddingScheme());
201
+		if (!$result) {
202
+			throw new \RuntimeException(
203
+				'openssl_private_decrypt() failed: ' .
204
+					 $this->_getLastOpenSSLError());
205
+		}
206
+		return $cek;
207
+	}
208
+
209
+	/**
210
+	 * Get last OpenSSL error message.
211
+	 *
212
+	 * @return null|string
213
+	 */
214
+	protected function _getLastOpenSSLError(): ?string
215
+	{
216
+		$msg = null;
217
+		while (false !== ($err = openssl_error_string())) {
218
+			$msg = $err;
219
+		}
220
+		return $msg;
221
+	}
222 222
 }
Please login to merge, or discard this patch.
lib/JWX/JWE/KeyAlgorithm/A192GCMKWAlgorithm.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -15,27 +15,27 @@
 block discarded – undo
15 15
  */
16 16
 class A192GCMKWAlgorithm extends AESGCMKWAlgorithm
17 17
 {
18
-    /**
19
-     * {@inheritdoc}
20
-     */
21
-    public function algorithmParamValue(): string
22
-    {
23
-        return JWA::ALGO_A192GCMKW;
24
-    }
18
+	/**
19
+	 * {@inheritdoc}
20
+	 */
21
+	public function algorithmParamValue(): string
22
+	{
23
+		return JWA::ALGO_A192GCMKW;
24
+	}
25 25
 
26
-    /**
27
-     * {@inheritdoc}
28
-     */
29
-    protected function _getGCMCipher(): Cipher
30
-    {
31
-        return new AES192Cipher();
32
-    }
26
+	/**
27
+	 * {@inheritdoc}
28
+	 */
29
+	protected function _getGCMCipher(): Cipher
30
+	{
31
+		return new AES192Cipher();
32
+	}
33 33
 
34
-    /**
35
-     * {@inheritdoc}
36
-     */
37
-    protected function _keySize(): int
38
-    {
39
-        return 24;
40
-    }
34
+	/**
35
+	 * {@inheritdoc}
36
+	 */
37
+	protected function _keySize(): int
38
+	{
39
+		return 24;
40
+	}
41 41
 }
Please login to merge, or discard this patch.
lib/JWX/JWE/KeyAlgorithm/PBES2HS256A128KWAlgorithm.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -15,35 +15,35 @@
 block discarded – undo
15 15
  */
16 16
 class PBES2HS256A128KWAlgorithm extends PBES2Algorithm
17 17
 {
18
-    /**
19
-     * {@inheritdoc}
20
-     */
21
-    public function algorithmParamValue(): string
22
-    {
23
-        return JWA::ALGO_PBES2_HS256_A128KW;
24
-    }
18
+	/**
19
+	 * {@inheritdoc}
20
+	 */
21
+	public function algorithmParamValue(): string
22
+	{
23
+		return JWA::ALGO_PBES2_HS256_A128KW;
24
+	}
25 25
 
26
-    /**
27
-     * {@inheritdoc}
28
-     */
29
-    protected function _hashAlgo(): string
30
-    {
31
-        return 'sha256';
32
-    }
26
+	/**
27
+	 * {@inheritdoc}
28
+	 */
29
+	protected function _hashAlgo(): string
30
+	{
31
+		return 'sha256';
32
+	}
33 33
 
34
-    /**
35
-     * {@inheritdoc}
36
-     */
37
-    protected function _keyLength(): int
38
-    {
39
-        return 16;
40
-    }
34
+	/**
35
+	 * {@inheritdoc}
36
+	 */
37
+	protected function _keyLength(): int
38
+	{
39
+		return 16;
40
+	}
41 41
 
42
-    /**
43
-     * {@inheritdoc}
44
-     */
45
-    protected function _kwAlgo(): AESKeyWrapAlgorithm
46
-    {
47
-        return new AESKW128();
48
-    }
42
+	/**
43
+	 * {@inheritdoc}
44
+	 */
45
+	protected function _kwAlgo(): AESKeyWrapAlgorithm
46
+	{
47
+		return new AESKW128();
48
+	}
49 49
 }
Please login to merge, or discard this patch.
lib/JWX/JWE/KeyAlgorithm/Feature/RandomCEK.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -9,21 +9,21 @@
 block discarded – undo
9 9
  */
10 10
 trait RandomCEK
11 11
 {
12
-    /**
13
-     * Generate a random content encryption key.
14
-     *
15
-     * @param int $length Key length in bytes
16
-     *
17
-     * @throws \RuntimeException
18
-     *
19
-     * @return string
20
-     */
21
-    public function cekForEncryption(int $length): string
22
-    {
23
-        $ret = openssl_random_pseudo_bytes($length);
24
-        if (false === $ret) {
25
-            throw new \RuntimeException('openssl_random_pseudo_bytes() failed.');
26
-        }
27
-        return $ret;
28
-    }
12
+	/**
13
+	 * Generate a random content encryption key.
14
+	 *
15
+	 * @param int $length Key length in bytes
16
+	 *
17
+	 * @throws \RuntimeException
18
+	 *
19
+	 * @return string
20
+	 */
21
+	public function cekForEncryption(int $length): string
22
+	{
23
+		$ret = openssl_random_pseudo_bytes($length);
24
+		if (false === $ret) {
25
+			throw new \RuntimeException('openssl_random_pseudo_bytes() failed.');
26
+		}
27
+		return $ret;
28
+	}
29 29
 }
Please login to merge, or discard this patch.
lib/JWX/JWE/KeyAlgorithm/AESGCMKWAlgorithm.php 1 patch
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -23,165 +23,165 @@
 block discarded – undo
23 23
  */
24 24
 abstract class AESGCMKWAlgorithm extends KeyManagementAlgorithm
25 25
 {
26
-    use RandomCEK;
27
-
28
-    /**
29
-     * Mapping from algorithm name to class name.
30
-     *
31
-     * @internal
32
-     *
33
-     * @var array
34
-     */
35
-    const MAP_ALGO_TO_CLASS = [
36
-        JWA::ALGO_A128GCMKW => A128GCMKWAlgorithm::class,
37
-        JWA::ALGO_A192GCMKW => A192GCMKWAlgorithm::class,
38
-        JWA::ALGO_A256GCMKW => A256GCMKWAlgorithm::class,
39
-    ];
40
-
41
-    /**
42
-     * Required IV size in bytes.
43
-     *
44
-     * @var int
45
-     */
46
-    const IV_SIZE = 12;
47
-
48
-    /**
49
-     * Authentication tag size in bytes.
50
-     *
51
-     * @var int
52
-     */
53
-    const AUTH_TAG_SIZE = 16;
54
-
55
-    /**
56
-     * Key encryption key.
57
-     *
58
-     * @var string
59
-     */
60
-    protected $_kek;
61
-
62
-    /**
63
-     * Initialization vector.
64
-     *
65
-     * @var string
66
-     */
67
-    protected $_iv;
68
-
69
-    /**
70
-     * Constructor.
71
-     *
72
-     * @param string $kek Key encryption key
73
-     * @param string $iv  Initialization vector
74
-     */
75
-    public function __construct(string $kek, string $iv)
76
-    {
77
-        if (strlen($kek) !== $this->_keySize()) {
78
-            throw new \LengthException('Invalid key size.');
79
-        }
80
-        if (self::IV_SIZE !== strlen($iv)) {
81
-            throw new \LengthException('Initialization vector must be 96 bits.');
82
-        }
83
-        $this->_kek = $kek;
84
-        $this->_iv = $iv;
85
-    }
86
-
87
-    /**
88
-     * Initialize from JWK.
89
-     *
90
-     * @param JWK    $jwk
91
-     * @param Header $header
92
-     *
93
-     * @throws \UnexpectedValueException
94
-     *
95
-     * @return self
96
-     */
97
-    public static function fromJWK(JWK $jwk, Header $header): KeyManagementAlgorithm
98
-    {
99
-        $jwk = SymmetricKeyJWK::fromJWK($jwk);
100
-        if (!$header->hasInitializationVector()) {
101
-            throw new \UnexpectedValueException('No initialization vector.');
102
-        }
103
-        $iv = $header->initializationVector()->initializationVector();
104
-        $alg = JWA::deriveAlgorithmName($header, $jwk);
105
-        if (!array_key_exists($alg, self::MAP_ALGO_TO_CLASS)) {
106
-            throw new \UnexpectedValueException("Unsupported algorithm '{$alg}'.");
107
-        }
108
-        $cls = self::MAP_ALGO_TO_CLASS[$alg];
109
-        return new $cls($jwk->key(), $iv);
110
-    }
111
-
112
-    /**
113
-     * Initialize from key encryption key with random IV.
114
-     *
115
-     * Key size must match the underlying cipher.
116
-     *
117
-     * @param string $key Key encryption key
118
-     *
119
-     * @return self
120
-     */
121
-    public static function fromKey(string $key): self
122
-    {
123
-        $iv = openssl_random_pseudo_bytes(self::IV_SIZE);
124
-        return new static($key, $iv);
125
-    }
126
-
127
-    /**
128
-     * {@inheritdoc}
129
-     */
130
-    public function headerParameters(): array
131
-    {
132
-        return array_merge(parent::headerParameters(),
133
-            [AlgorithmParameter::fromAlgorithm($this),
134
-                InitializationVectorParameter::fromString($this->_iv), ]);
135
-    }
136
-
137
-    /**
138
-     * Get GCM Cipher instance.
139
-     *
140
-     * @return Cipher
141
-     */
142
-    abstract protected function _getGCMCipher(): Cipher;
143
-
144
-    /**
145
-     * Get the required key size.
146
-     *
147
-     * @return int
148
-     */
149
-    abstract protected function _keySize(): int;
150
-
151
-    /**
152
-     * Get GCM instance.
153
-     *
154
-     * @return GCM
155
-     */
156
-    final protected function _getGCM(): GCM
157
-    {
158
-        return new GCM($this->_getGCMCipher(), self::AUTH_TAG_SIZE);
159
-    }
160
-
161
-    /**
162
-     * {@inheritdoc}
163
-     */
164
-    protected function _encryptKey(string $key, Header &$header): string
165
-    {
166
-        [$ciphertext, $auth_tag] = $this->_getGCM()
167
-            ->encrypt($key, '', $this->_kek, $this->_iv);
168
-        // insert authentication tag to the header
169
-        $header = $header->withParameters(
170
-            AuthenticationTagParameter::fromString($auth_tag));
171
-        return $ciphertext;
172
-    }
173
-
174
-    /**
175
-     * {@inheritdoc}
176
-     */
177
-    protected function _decryptKey(string $ciphertext, Header $header): string
178
-    {
179
-        if (!$header->hasAuthenticationTag()) {
180
-            throw new \RuntimeException(
181
-                "Header doesn't contain authentication tag.");
182
-        }
183
-        $auth_tag = $header->authenticationTag()->authenticationTag();
184
-        return $this->_getGCM()
185
-            ->decrypt($ciphertext, $auth_tag, '', $this->_kek, $this->_iv);
186
-    }
26
+	use RandomCEK;
27
+
28
+	/**
29
+	 * Mapping from algorithm name to class name.
30
+	 *
31
+	 * @internal
32
+	 *
33
+	 * @var array
34
+	 */
35
+	const MAP_ALGO_TO_CLASS = [
36
+		JWA::ALGO_A128GCMKW => A128GCMKWAlgorithm::class,
37
+		JWA::ALGO_A192GCMKW => A192GCMKWAlgorithm::class,
38
+		JWA::ALGO_A256GCMKW => A256GCMKWAlgorithm::class,
39
+	];
40
+
41
+	/**
42
+	 * Required IV size in bytes.
43
+	 *
44
+	 * @var int
45
+	 */
46
+	const IV_SIZE = 12;
47
+
48
+	/**
49
+	 * Authentication tag size in bytes.
50
+	 *
51
+	 * @var int
52
+	 */
53
+	const AUTH_TAG_SIZE = 16;
54
+
55
+	/**
56
+	 * Key encryption key.
57
+	 *
58
+	 * @var string
59
+	 */
60
+	protected $_kek;
61
+
62
+	/**
63
+	 * Initialization vector.
64
+	 *
65
+	 * @var string
66
+	 */
67
+	protected $_iv;
68
+
69
+	/**
70
+	 * Constructor.
71
+	 *
72
+	 * @param string $kek Key encryption key
73
+	 * @param string $iv  Initialization vector
74
+	 */
75
+	public function __construct(string $kek, string $iv)
76
+	{
77
+		if (strlen($kek) !== $this->_keySize()) {
78
+			throw new \LengthException('Invalid key size.');
79
+		}
80
+		if (self::IV_SIZE !== strlen($iv)) {
81
+			throw new \LengthException('Initialization vector must be 96 bits.');
82
+		}
83
+		$this->_kek = $kek;
84
+		$this->_iv = $iv;
85
+	}
86
+
87
+	/**
88
+	 * Initialize from JWK.
89
+	 *
90
+	 * @param JWK    $jwk
91
+	 * @param Header $header
92
+	 *
93
+	 * @throws \UnexpectedValueException
94
+	 *
95
+	 * @return self
96
+	 */
97
+	public static function fromJWK(JWK $jwk, Header $header): KeyManagementAlgorithm
98
+	{
99
+		$jwk = SymmetricKeyJWK::fromJWK($jwk);
100
+		if (!$header->hasInitializationVector()) {
101
+			throw new \UnexpectedValueException('No initialization vector.');
102
+		}
103
+		$iv = $header->initializationVector()->initializationVector();
104
+		$alg = JWA::deriveAlgorithmName($header, $jwk);
105
+		if (!array_key_exists($alg, self::MAP_ALGO_TO_CLASS)) {
106
+			throw new \UnexpectedValueException("Unsupported algorithm '{$alg}'.");
107
+		}
108
+		$cls = self::MAP_ALGO_TO_CLASS[$alg];
109
+		return new $cls($jwk->key(), $iv);
110
+	}
111
+
112
+	/**
113
+	 * Initialize from key encryption key with random IV.
114
+	 *
115
+	 * Key size must match the underlying cipher.
116
+	 *
117
+	 * @param string $key Key encryption key
118
+	 *
119
+	 * @return self
120
+	 */
121
+	public static function fromKey(string $key): self
122
+	{
123
+		$iv = openssl_random_pseudo_bytes(self::IV_SIZE);
124
+		return new static($key, $iv);
125
+	}
126
+
127
+	/**
128
+	 * {@inheritdoc}
129
+	 */
130
+	public function headerParameters(): array
131
+	{
132
+		return array_merge(parent::headerParameters(),
133
+			[AlgorithmParameter::fromAlgorithm($this),
134
+				InitializationVectorParameter::fromString($this->_iv), ]);
135
+	}
136
+
137
+	/**
138
+	 * Get GCM Cipher instance.
139
+	 *
140
+	 * @return Cipher
141
+	 */
142
+	abstract protected function _getGCMCipher(): Cipher;
143
+
144
+	/**
145
+	 * Get the required key size.
146
+	 *
147
+	 * @return int
148
+	 */
149
+	abstract protected function _keySize(): int;
150
+
151
+	/**
152
+	 * Get GCM instance.
153
+	 *
154
+	 * @return GCM
155
+	 */
156
+	final protected function _getGCM(): GCM
157
+	{
158
+		return new GCM($this->_getGCMCipher(), self::AUTH_TAG_SIZE);
159
+	}
160
+
161
+	/**
162
+	 * {@inheritdoc}
163
+	 */
164
+	protected function _encryptKey(string $key, Header &$header): string
165
+	{
166
+		[$ciphertext, $auth_tag] = $this->_getGCM()
167
+			->encrypt($key, '', $this->_kek, $this->_iv);
168
+		// insert authentication tag to the header
169
+		$header = $header->withParameters(
170
+			AuthenticationTagParameter::fromString($auth_tag));
171
+		return $ciphertext;
172
+	}
173
+
174
+	/**
175
+	 * {@inheritdoc}
176
+	 */
177
+	protected function _decryptKey(string $ciphertext, Header $header): string
178
+	{
179
+		if (!$header->hasAuthenticationTag()) {
180
+			throw new \RuntimeException(
181
+				"Header doesn't contain authentication tag.");
182
+		}
183
+		$auth_tag = $header->authenticationTag()->authenticationTag();
184
+		return $this->_getGCM()
185
+			->decrypt($ciphertext, $auth_tag, '', $this->_kek, $this->_iv);
186
+	}
187 187
 }
Please login to merge, or discard this patch.
lib/JWX/JWE/KeyAlgorithm/A128KWAlgorithm.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -15,27 +15,27 @@
 block discarded – undo
15 15
  */
16 16
 class A128KWAlgorithm extends AESKWAlgorithm
17 17
 {
18
-    /**
19
-     * {@inheritdoc}
20
-     */
21
-    public function algorithmParamValue(): string
22
-    {
23
-        return JWA::ALGO_A128KW;
24
-    }
18
+	/**
19
+	 * {@inheritdoc}
20
+	 */
21
+	public function algorithmParamValue(): string
22
+	{
23
+		return JWA::ALGO_A128KW;
24
+	}
25 25
 
26
-    /**
27
-     * {@inheritdoc}
28
-     */
29
-    protected function _kekSize(): int
30
-    {
31
-        return 16;
32
-    }
26
+	/**
27
+	 * {@inheritdoc}
28
+	 */
29
+	protected function _kekSize(): int
30
+	{
31
+		return 16;
32
+	}
33 33
 
34
-    /**
35
-     * {@inheritdoc}
36
-     */
37
-    protected function _AESKWAlgo(): AESKeyWrapAlgorithm
38
-    {
39
-        return new AESKW128();
40
-    }
34
+	/**
35
+	 * {@inheritdoc}
36
+	 */
37
+	protected function _AESKWAlgo(): AESKeyWrapAlgorithm
38
+	{
39
+		return new AESKW128();
40
+	}
41 41
 }
Please login to merge, or discard this patch.