mirror of
https://github.com/elyby/oauth2-server.git
synced 2025-01-03 18:51:53 +05:30
Merge pull request #625 from juliangut/key-file
Key file auto-generation from string
This commit is contained in:
commit
9dee08ba3d
@ -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
36
tests/CryptKeyTest.php
Normal 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()
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user