|
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
|
|
|
private function __construct() |
|
19
|
|
|
{ |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
public static function generateKeyPair($keySize = 1024): RsaKeyPair |
|
23
|
|
|
{ |
|
24
|
|
|
if (self::$instance === null) |
|
25
|
|
|
self::$instance = new RsaGenerator(); |
|
26
|
|
|
|
|
27
|
|
|
return self::$instance->generate($keySize); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
private function generate($keySize) |
|
31
|
|
|
{ |
|
32
|
|
|
$rsaKey = openssl_pkey_new(array( |
|
33
|
|
|
'private_key_bits' => $keySize, |
|
34
|
|
|
'private_key_type' => OPENSSL_KEYTYPE_RSA)); |
|
35
|
|
|
|
|
36
|
|
|
$privKey = openssl_pkey_get_private($rsaKey); |
|
37
|
|
|
openssl_pkey_export($privKey, $pem); //Private Key |
|
38
|
|
|
$pubKey = $this->sshEncodePublicKey($rsaKey); //Public Key |
|
39
|
|
|
|
|
40
|
|
|
$umask = umask(0066); |
|
|
|
|
|
|
41
|
|
|
return new RsaKeyPair(str_replace(PHP_EOL, '', $pubKey), str_replace(PHP_EOL, '', $pem)); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
private function sshEncodePublicKey($privKey) |
|
45
|
|
|
{ |
|
46
|
|
|
$keyInfo = openssl_pkey_get_details($privKey); |
|
47
|
|
|
$buffer = pack("N", 7) . "ssh-rsa" . |
|
48
|
|
|
$this->sshEncodeBuffer($keyInfo['rsa']['e']) . |
|
49
|
|
|
$this->sshEncodeBuffer($keyInfo['rsa']['n']); |
|
50
|
|
|
return "ssh-rsa " . base64_encode($buffer); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
private function sshEncodeBuffer($buffer) |
|
54
|
|
|
{ |
|
55
|
|
|
$len = strlen($buffer); |
|
56
|
|
|
if (ord($buffer[0]) & 0x80) { |
|
57
|
|
|
$len++; |
|
58
|
|
|
$buffer = "\x00" . $buffer; |
|
59
|
|
|
} |
|
60
|
|
|
return pack("Na*", $len, $buffer); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|