diff --git a/src/CryptKey.php b/src/CryptKey.php index e088abcf..aedeafb0 100644 --- a/src/CryptKey.php +++ b/src/CryptKey.php @@ -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. * diff --git a/tests/CryptKeyTest.php b/tests/CryptKeyTest.php new file mode 100644 index 00000000..c7f7f4a0 --- /dev/null +++ b/tests/CryptKeyTest.php @@ -0,0 +1,36 @@ +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() + ); + } +}