Skip to content

Commit

Permalink
Add support of the OpenSSLAsymmetricKey object
Browse files Browse the repository at this point in the history
  • Loading branch information
DmytroKlymanSpryker committed Jul 7, 2023
1 parent eb91b41 commit 786e145
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/CryptKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class CryptKey
private const FILE_PREFIX = 'file://';

/**
* @var string Key contents
* @var string|\OpenSSLAsymmetricKey Key contents
*/
protected $keyContents;

Expand All @@ -37,15 +37,17 @@ class CryptKey
protected $passPhrase;

/**
* @param string $keyPath
* @param null|string $passPhrase
* @param bool $keyPermissionsCheck
* @param string|\OpenSSLAsymmetricKey $keyPath
* @param null|string $passPhrase
* @param bool $keyPermissionsCheck
*/
public function __construct($keyPath, $passPhrase = null, $keyPermissionsCheck = true)
{
$this->passPhrase = $passPhrase;

if (\strpos($keyPath, self::FILE_PREFIX) !== 0 && $this->isValidKey($keyPath, $this->passPhrase ?? '')) {
if ($keyPath instanceof \OpenSSLAsymmetricKey
|| (\strpos($keyPath, self::FILE_PREFIX) !== 0 && $this->isValidKey($keyPath, $this->passPhrase ?? ''))
) {
$this->keyContents = $keyPath;
$this->keyPath = '';
// There's no file, so no need for permission check.
Expand Down Expand Up @@ -86,9 +88,9 @@ public function __construct($keyPath, $passPhrase = null, $keyPermissionsCheck =
/**
* Get key contents
*
* @return string Key contents
* @return string|\OpenSSLAsymmetricKey Key contents
*/
public function getKeyContents(): string
public function getKeyContents()
{
return $this->keyContents;
}
Expand Down
17 changes: 17 additions & 0 deletions tests/Utils/CryptKeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,23 @@ public function testNoFile()
new CryptKey('undefined file');
}

public function testKeyOpenSSLAsymmetricKeyObject()
{
$publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoKQH6XtTUYPSIWPjtcA3I6VBF3F3TZMd9RImq0YG55qGIJvOOP0MeVib
D7MFtN4hv6ke3NyYaaUfRaxQ6mrDGzd
YOzdkqebjUzSNnwd8eQCRL2rvOsgUhf2yghLBlxq+9yfpzDV3KQ58JkCqvV1trBt/ISjPtgbK24V3v55z+cN558DMgyQmV
8pYrTFzktFVlJP20DR08HzIGimlWq/ixUfY4K
rznqapnKMw1u6SVVgGem67LC8HO9Mfx3KDseJaG7oUbSWq8vaTW2ewjEfs5JRt1OMUol7CHHtqVprcMizclqCO9Kh
Dmpussq19l0LbKbGkC73uK0Nm8RyfGhiWCQIDAQAB
-----END PUBLIC KEY-----';

$openSSLAsymmetricKey = openssl_get_publickey($publicKey);
$key = new CryptKey($openSSLAsymmetricKey);

$this->assertEquals($openSSLAsymmetricKey, $key->getKeyContents());
}

public function testKeyCreation()
{
$keyFile = __DIR__ . '/../Stubs/public.key';
Expand Down

0 comments on commit 786e145

Please sign in to comment.