1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Sop\CryptoTypes\Asymmetric; |
6
|
|
|
|
7
|
|
|
use Sop\CryptoEncoding\PEM; |
8
|
|
|
use Sop\CryptoTypes\AlgorithmIdentifier\Feature\AlgorithmIdentifierType; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Base class for private keys. |
12
|
|
|
*/ |
13
|
|
|
abstract class PrivateKey |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Get the private key algorithm identifier. |
17
|
|
|
* |
18
|
|
|
* @return AlgorithmIdentifierType |
19
|
|
|
*/ |
20
|
|
|
abstract public function algorithmIdentifier(): AlgorithmIdentifierType; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Get public key component of the asymmetric key pair. |
24
|
|
|
* |
25
|
|
|
* @return PublicKey |
26
|
|
|
*/ |
27
|
|
|
abstract public function publicKey(): PublicKey; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Get DER encoding of the private key. |
31
|
|
|
* |
32
|
|
|
* @return string |
33
|
|
|
*/ |
34
|
|
|
abstract public function toDER(): string; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Get the private key as a PEM. |
38
|
|
|
* |
39
|
|
|
* @return PEM |
40
|
|
|
*/ |
41
|
|
|
abstract public function toPEM(): PEM; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Get the private key as a PrivateKeyInfo type. |
45
|
|
|
* |
46
|
|
|
* @return PrivateKeyInfo |
47
|
|
|
*/ |
48
|
2 |
|
public function privateKeyInfo(): PrivateKeyInfo |
49
|
|
|
{ |
50
|
2 |
|
return PrivateKeyInfo::fromPrivateKey($this); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Initialize private key from PEM. |
55
|
|
|
* |
56
|
|
|
* @param PEM $pem |
57
|
|
|
* |
58
|
|
|
* @throws \UnexpectedValueException |
59
|
|
|
* |
60
|
|
|
* @return PrivateKey |
61
|
|
|
*/ |
62
|
13 |
|
public static function fromPEM(PEM $pem) |
63
|
|
|
{ |
64
|
13 |
|
switch ($pem->type()) { |
65
|
13 |
|
case PEM::TYPE_RSA_PRIVATE_KEY: |
66
|
2 |
|
return RSA\RSAPrivateKey::fromDER($pem->data()); |
67
|
11 |
|
case PEM::TYPE_EC_PRIVATE_KEY: |
68
|
2 |
|
return EC\ECPrivateKey::fromDER($pem->data()); |
69
|
9 |
|
case PEM::TYPE_PRIVATE_KEY: |
70
|
6 |
|
return PrivateKeyInfo::fromDER($pem->data())->privateKey(); |
71
|
|
|
} |
72
|
3 |
|
throw new \UnexpectedValueException( |
73
|
3 |
|
'PEM type ' . $pem->type() . ' is not a valid private key.'); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|