Completed
Pull Request — master (#625)
by Julián
35:10
created

CryptKey::getPassPhrase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * Cryptography key holder.
4
 *
5
 * @author      Julián Gutiérrez <[email protected]>
6
 * @copyright   Copyright (c) Alex Bilbie
7
 * @license     http://mit-license.org/
8
 *
9
 * @link        https://github.com/thephpleague/oauth2-server
10
 */
11
12
namespace League\OAuth2\Server;
13
14
class CryptKey
15
{
16
    const RSA_KEY_PATTERN =
17
        '/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----\n)(.|\n)+(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)$/';
18
19
    /**
20
     * @var string
21
     */
22
    protected $keyPath;
23
24
    /**
25
     * @var null|string
26
     */
27
    protected $passPhrase;
28
29
    /**
30
     * @param string      $keyPath
31
     * @param null|string $passPhrase
32
     */
33
    public function __construct($keyPath, $passPhrase = null)
34
    {
35
        if (preg_match(self::RSA_KEY_PATTERN, $keyPath)) {
36
            $keyPath = $this->saveKeyToFile($keyPath);
37
        }
38
39
        if (strpos($keyPath, 'file://') !== 0) {
40
            $keyPath = 'file://' . $keyPath;
41
        }
42
43
        if (!file_exists($keyPath) || !is_readable($keyPath)) {
44
            throw new \LogicException(sprintf('Key path "%s" does not exist or is not readable', $keyPath));
45
        }
46
47
        $this->keyPath = $keyPath;
48
        $this->passPhrase = $passPhrase;
49
    }
50
51
    /**
52
     * @param string $key
53
     *
54
     * @throws \RuntimeException
55
     *
56
     * @return string
57
     */
58
    private function saveKeyToFile($key)
59
    {
60
        $keyPath = sys_get_temp_dir() . '/' . sha1($key) . '.key';
61
62
        if (!file_exists($keyPath) && !touch($keyPath)) {
63
            // @codeCoverageIgnoreStart
64
            throw new \RuntimeException('"%s" key file could not be created', $keyPath);
65
            // @codeCoverageIgnoreEnd
66
        }
67
68
        file_put_contents($keyPath, $key);
69
70
        return 'file://' . $keyPath;
71
    }
72
73
    /**
74
     * Retrieve key path.
75
     *
76
     * @return string
77
     */
78
    public function getKeyPath()
79
    {
80
        return $this->keyPath;
81
    }
82
83
    /**
84
     * Retrieve key pass phrase.
85
     *
86
     * @return null|string
87
     */
88
    public function getPassPhrase()
89
    {
90
        return $this->passPhrase;
91
    }
92
}
93