From dacf799861d5bac9f98938f467609d3f5008ee1f Mon Sep 17 00:00:00 2001 From: Tim van Dijen Date: Sun, 1 Sep 2024 16:24:12 +0200 Subject: [PATCH] Prefix filenames with file:// if necessary, or openssl will fail --- src/Key/PrivateKey.php | 6 ++++++ tests/Key/PrivateKeyTest.php | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/Key/PrivateKey.php b/src/Key/PrivateKey.php index 28a89f97..4177babf 100644 --- a/src/Key/PrivateKey.php +++ b/src/Key/PrivateKey.php @@ -10,6 +10,8 @@ use function openssl_pkey_export; use function openssl_pkey_get_private; +use function preg_filter; +use function preg_match; /** * A class modeling private keys for their use in asymmetric algorithms. @@ -52,6 +54,10 @@ public static function fromFile( #[\SensitiveParameter] string $passphrase = '', ): static { + if (preg_match('/^(file:\/\/)/i', $file) !== 1) { + $file = preg_filter('/^/', 'file://', $file); + } + if (($key = openssl_pkey_get_private($file, $passphrase)) === false) { throw new OpenSSLException('Failed to read key'); } diff --git a/tests/Key/PrivateKeyTest.php b/tests/Key/PrivateKeyTest.php index 4fd274ed..87fffcdf 100644 --- a/tests/Key/PrivateKeyTest.php +++ b/tests/Key/PrivateKeyTest.php @@ -56,4 +56,15 @@ public function testFromFile(): void $keyDetails = openssl_pkey_get_details(openssl_pkey_get_private($k->getMaterial())); $this->assertEquals(self::$privKey['key'], $keyDetails['key']); } + + + /** + * Test creation from a file without file:// prefix succeeds. + */ + public function testFromFileNoPrefix(): void + { + $k = PrivateKey::fromFile('./resources/keys/privkey.pem'); + $keyDetails = openssl_pkey_get_details(openssl_pkey_get_private($k->getMaterial())); + $this->assertEquals(self::$privKey['key'], $keyDetails['key']); + } }