Merge pull request #625 from juliangut/key-file

Key file auto-generation from string
This commit is contained in:
Alex Bilbie 2016-07-19 17:24:12 +01:00 committed by GitHub
commit 9dee08ba3d
2 changed files with 65 additions and 0 deletions

View File

@ -13,6 +13,9 @@ namespace League\OAuth2\Server;
class CryptKey
{
const RSA_KEY_PATTERN =
'/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----\n)(.|\n)+(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)$/';
/**
* @var string
*/
@ -29,6 +32,10 @@ class CryptKey
*/
public function __construct($keyPath, $passPhrase = null)
{
if (preg_match(self::RSA_KEY_PATTERN, $keyPath)) {
$keyPath = $this->saveKeyToFile($keyPath);
}
if (strpos($keyPath, 'file://') !== 0) {
$keyPath = 'file://' . $keyPath;
}
@ -41,6 +48,28 @@ class CryptKey
$this->passPhrase = $passPhrase;
}
/**
* @param string $key
*
* @throws \RuntimeException
*
* @return string
*/
private function saveKeyToFile($key)
{
$keyPath = sys_get_temp_dir() . '/' . sha1($key) . '.key';
if (!file_exists($keyPath) && !touch($keyPath)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('"%s" key file could not be created', $keyPath);
// @codeCoverageIgnoreEnd
}
file_put_contents($keyPath, $key);
return 'file://' . $keyPath;
}
/**
* Retrieve key path.
*

36
tests/CryptKeyTest.php Normal file
View File

@ -0,0 +1,36 @@
<?php
namespace LeagueTests\Utils;
use League\OAuth2\Server\CryptKey;
class CryptKeyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \LogicException
*/
public function testNoFile()
{
new CryptKey('undefined file');
}
public function testKeyCreation()
{
$keyFile = __DIR__ . '/Stubs/public.key';
$key = new CryptKey($keyFile, 'secret');
$this->assertEquals('file://' . $keyFile, $key->getKeyPath());
$this->assertEquals('secret', $key->getPassPhrase());
}
public function testKeyFileCreation()
{
$keyContent = file_get_contents(__DIR__ . '/Stubs/public.key');
$key = new CryptKey($keyContent);
$this->assertEquals(
'file://' . sys_get_temp_dir() . '/' . sha1($keyContent) . '.key',
$key->getKeyPath()
);
}
}