Skip to content

Commit

Permalink
Merge pull request #4 from eislasq/master
Browse files Browse the repository at this point in the history
Support to load Pkcs8 key as is. #3
  • Loading branch information
eclipxe13 committed Nov 14, 2019
2 parents 3c15203 + 01aaff2 commit fc920c5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
16 changes: 12 additions & 4 deletions src/PrivateKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,19 @@ public function __construct(string $source, string $passPhrase)
throw new UnexpectedValueException('Private key is empty');
}
$pemExtractor = new PemExtractor($source);
$source = $pemExtractor->extractPrivateKey();
if ('' === $source) {
throw new UnexpectedValueException('Private key is not PEM');
$private = $pemExtractor->extractPrivateKey();
if ('' === $private) {
if (boolval(preg_match('/^[a-zA-Z0-9+\/]+={0,2}$/', $source))) {
// if contents are base64 encoded, then decode it
$source = base64_decode($source, true) ?: '';
}
$pem = '-----BEGIN ENCRYPTED PRIVATE KEY-----' . PHP_EOL
. chunk_split(base64_encode($source), 64, PHP_EOL)
. '-----END ENCRYPTED PRIVATE KEY-----';
} else {
$pem = $private;
}
$this->pem = $source;
$this->pem = $pem;
$this->passPhrase = $passPhrase;
$dataArray = $this->callOnPrivateKey(
function ($privateKey): array {
Expand Down
24 changes: 20 additions & 4 deletions tests/Unit/PrivateKeyConstructTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,31 @@ public function testConstructWithEmptyContent(): void

public function testConstructWithInvalidContent(): void
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Private key is not PEM');
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Cannot open private key');
new PrivateKey('invalid content', '');
}

public function testConstructWithInvalidButBase64Content(): void
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Private key is not PEM');
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Cannot open private key');
new PrivateKey('INVALID+CONTENT', '');
}

public function testConstructWithPkcs8Content(): void
{
$content = $this->fileContents('CSD01_AAA010101AAA/private_key.key');
$password = trim($this->fileContents('CSD01_AAA010101AAA/password.txt'));
$privateKey = new PrivateKey($content, $password);
$this->assertGreaterThan(0, $privateKey->numberOfBits());
}

public function testConstructWithPkcs8Base64Content(): void
{
$content = base64_encode($this->fileContents('CSD01_AAA010101AAA/private_key.key'));
$password = trim($this->fileContents('CSD01_AAA010101AAA/password.txt'));
$privateKey = new PrivateKey($content, $password);
$this->assertGreaterThan(0, $privateKey->numberOfBits());
}
}

0 comments on commit fc920c5

Please sign in to comment.