From 69586ceb8fe7d4dfe75181a263f31e14ac9f5776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Djupsj=C3=B6backa?= Date: Wed, 17 Apr 2024 16:12:30 +0300 Subject: [PATCH] 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 --- KeyManagement/KeyConverter/KeyConverter.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/KeyManagement/KeyConverter/KeyConverter.php b/KeyManagement/KeyConverter/KeyConverter.php index 010c7ab..d7a0238 100644 --- a/KeyManagement/KeyConverter/KeyConverter.php +++ b/KeyManagement/KeyConverter/KeyConverter.php @@ -365,7 +365,11 @@ private static function getCurve(string $oid): string */ private static function sanitizePEM(string &$pem): void { - preg_match_all('#(-.*-)#', $pem, $matches, PREG_PATTERN_ORDER); + $number = preg_match_all('#(-.*-)#', $pem, $matches, PREG_PATTERN_ORDER); + if ($number !== 2) { + throw new InvalidArgumentException('Unable to load the key'); + } + $ciphertext = preg_replace('#-.*-|\r|\n| #', '', $pem); $pem = $matches[0][0] . PHP_EOL;