Skip to content

Commit

Permalink
Prefix filenames with file:// if necessary, or openssl will fail
Browse files Browse the repository at this point in the history
  • Loading branch information
tvdijen committed Sep 1, 2024
1 parent 546a3f0 commit a168043
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Key/PrivateKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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');
}
Expand Down
11 changes: 11 additions & 0 deletions tests/Key/PrivateKeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
}
}

0 comments on commit a168043

Please sign in to comment.