Skip to content

Commit cdeb1f5

Browse files
crocodeleSpomky
andauthored
Avoid PHP warnings about undefined array keys when sanitizing malformed PEMs (#556)
* Avoid PHP warnings about undefined indexes when sanitizing malformed PEMs * Add test for loading invalid PEM key A new test function was added in ECKeysTest.php to handle cases of loading invalid PEM keys. An InvalidArgumentException is expected to be thrown with a specific error message when an invalid private PEM key is loaded. --------- Co-authored-by: Florent Morselli <[email protected]>
1 parent 8342de7 commit cdeb1f5

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/Library/KeyManagement/KeyConverter/KeyConverter.php

+5-1
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,11 @@ private static function getCurve(string $oid): string
365365
*/
366366
private static function sanitizePEM(string &$pem): void
367367
{
368-
preg_match_all('#(-.*-)#', $pem, $matches, PREG_PATTERN_ORDER);
368+
$number = preg_match_all('#(-.*-)#', $pem, $matches, PREG_PATTERN_ORDER);
369+
if ($number !== 2) {
370+
throw new InvalidArgumentException('Unable to load the key');
371+
}
372+
369373
$ciphertext = preg_replace('#-.*-|\r|\n| #', '', $pem);
370374

371375
$pem = $matches[0][0] . PHP_EOL;

tests/Component/KeyManagement/Keys/ECKeysTest.php

+25
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,31 @@ public function loadEncryptedPrivateEC512Key(): void
208208
]);
209209
}
210210

211+
#[Test]
212+
public function loadInvalidPEMKey(): void
213+
{
214+
// Then
215+
$this->expectException(InvalidArgumentException::class);
216+
$this->expectExceptionMessage('Unable to load the key');
217+
218+
// Given
219+
$private_pem = trim(<<<PEM
220+
MIIB0jCCAXegAwIBAgIJAK2o1kQ5JwpUMAoGCCqGSM49BAMCMEUxCzAJBgNVBAYT
221+
AkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRn
222+
aXRzIFB0eSBMdGQwHhcNMTUxMTA4MTUxMTU2WhcNMTYxMTA3MTUxMTU2WjBFMQsw
223+
CQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJu
224+
ZXQgV2lkZ2l0cyBQdHkgTHRkMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAExEsr
225+
/55aqgFXdrbRNz1/WSNI8UaSUxCka2kGEN1bXsJIzjkeyv12dRHo7H5OmY2/Z9sN
226+
fgKhWj7elq0xSlcA0KNQME4wHQYDVR0OBBYEFKIGgCZoS388STT0qjoX/swKYBXh
227+
MB8GA1UdIwQYMBaAFKIGgCZoS388STT0qjoX/swKYBXhMAwGA1UdEwQFMAMBAf8w
228+
CgYIKoZIzj0EAwIDSQAwRgIhAK5OqQoBGR/pj2NOb+PyRKK4k4d3Muj9z/6LsJK+
229+
kkgUAiEA+FY4SWKv4mfe0gsOBId0Aah/HtVZxDBe3bCXOQM8MMM=
230+
PEM);
231+
232+
// When
233+
KeyConverter::loadFromKey($private_pem, 'test');
234+
}
235+
211236
#[Test]
212237
public function convertPrivateKeyToPublic(): void
213238
{

0 commit comments

Comments
 (0)