oauth2-server/src/CryptKey.php

93 lines
2.0 KiB
PHP
Raw Normal View History

2016-03-28 16:42:34 +02:00
<?php
/**
* Cryptography key holder.
*
* @author Julián Gutiérrez <juliangut@gmail.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
2016-07-09 01:00:44 +02:00
2016-03-28 16:42:34 +02:00
namespace League\OAuth2\Server;
class CryptKey
{
2016-07-19 15:01:31 +02:00
const RSA_KEY_PATTERN =
'/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----\n)(.|\n)+(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)$/';
2016-03-28 16:42:34 +02:00
/**
* @var string
*/
protected $keyPath;
/**
2016-07-09 01:00:44 +02:00
* @var null|string
2016-03-28 16:42:34 +02:00
*/
protected $passPhrase;
/**
* @param string $keyPath
* @param null|string $passPhrase
*/
public function __construct($keyPath, $passPhrase = null)
{
2016-07-19 15:01:31 +02:00
if (preg_match(self::RSA_KEY_PATTERN, $keyPath)) {
$keyPath = $this->saveKeyToFile($keyPath);
}
2016-03-28 16:42:34 +02:00
if (strpos($keyPath, 'file://') !== 0) {
$keyPath = 'file://' . $keyPath;
}
if (!file_exists($keyPath) || !is_readable($keyPath)) {
throw new \LogicException(sprintf('Key path "%s" does not exist or is not readable', $keyPath));
}
$this->keyPath = $keyPath;
$this->passPhrase = $passPhrase;
}
2016-07-19 15:01:31 +02:00
/**
* @param string $key
*
2016-07-19 17:15:36 +02:00
* @throws \RuntimeException
*
2016-07-19 15:01:31 +02:00
* @return string
*/
private function saveKeyToFile($key)
{
$keyPath = sys_get_temp_dir() . '/' . sha1($key) . '.key';
2016-07-19 15:06:32 +02:00
if (!file_exists($keyPath) && !touch($keyPath)) {
2016-07-19 17:15:36 +02:00
// @codeCoverageIgnoreStart
2016-07-19 15:01:31 +02:00
throw new \RuntimeException('"%s" key file could not be created', $keyPath);
2016-07-19 17:15:36 +02:00
// @codeCoverageIgnoreEnd
2016-07-19 15:01:31 +02:00
}
file_put_contents($keyPath, $key);
return 'file://' . $keyPath;
}
2016-03-28 16:42:34 +02:00
/**
* Retrieve key path.
*
* @return string
*/
public function getKeyPath()
{
return $this->keyPath;
}
/**
* Retrieve key pass phrase.
*
* @return null|string
*/
public function getPassPhrase()
{
return $this->passPhrase;
}
}