1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: arthur |
5
|
|
|
* Date: 24/10/17 |
6
|
|
|
* Time: 20:07 |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Modules\Script\Support; |
10
|
|
|
|
11
|
|
|
class RsaGenerator |
12
|
|
|
{ |
13
|
|
|
private static $instance; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* RsaGenerator constructor. |
17
|
|
|
*/ |
18
|
1 |
|
private function __construct() |
19
|
|
|
{ |
20
|
1 |
|
} |
21
|
|
|
|
22
|
11 |
|
public static function generateKeyPair($keySize = 1024): RsaKeyPair |
23
|
|
|
{ |
24
|
11 |
|
if (self::$instance === null) |
25
|
1 |
|
self::$instance = new RsaGenerator(); |
26
|
|
|
|
27
|
11 |
|
return self::$instance->generate($keySize); |
28
|
|
|
} |
29
|
|
|
|
30
|
11 |
|
private function generate($keySize) |
31
|
|
|
{ |
32
|
11 |
|
$rsaKey = openssl_pkey_new(array( |
33
|
11 |
|
'private_key_bits' => $keySize, |
34
|
11 |
|
'private_key_type' => OPENSSL_KEYTYPE_RSA)); |
35
|
|
|
|
36
|
11 |
|
$privKey = openssl_pkey_get_private($rsaKey); |
37
|
11 |
|
openssl_pkey_export($privKey, $pem); //Private Key |
38
|
11 |
|
$pubKey = $this->sshEncodePublicKey($rsaKey); //Public Key |
39
|
|
|
|
40
|
11 |
|
$umask = umask(0066); |
|
|
|
|
41
|
11 |
|
return new RsaKeyPair(str_replace(PHP_EOL, '', $pubKey), str_replace(PHP_EOL, '', $pem)); |
42
|
|
|
} |
43
|
|
|
|
44
|
11 |
|
private function sshEncodePublicKey($privKey) |
45
|
|
|
{ |
46
|
11 |
|
$keyInfo = openssl_pkey_get_details($privKey); |
47
|
11 |
|
$buffer = pack("N", 7) . "ssh-rsa" . |
48
|
11 |
|
$this->sshEncodeBuffer($keyInfo['rsa']['e']) . |
49
|
11 |
|
$this->sshEncodeBuffer($keyInfo['rsa']['n']); |
50
|
11 |
|
return "ssh-rsa " . base64_encode($buffer); |
51
|
|
|
} |
52
|
|
|
|
53
|
11 |
|
private function sshEncodeBuffer($buffer) |
54
|
|
|
{ |
55
|
11 |
|
$len = strlen($buffer); |
56
|
11 |
|
if (ord($buffer[0]) & 0x80) { |
57
|
11 |
|
$len++; |
58
|
11 |
|
$buffer = "\x00" . $buffer; |
59
|
|
|
} |
60
|
11 |
|
return pack("Na*", $len, $buffer); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|