RsaGenerator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 50
ccs 0
cts 36
cp 0
rs 10
c 0
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A sshEncodePublicKey() 0 7 1
A sshEncodeBuffer() 0 8 2
A generateKeyPair() 0 6 2
A generate() 0 12 1
A __construct() 0 2 1
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);
0 ignored issues
show
Unused Code introduced by
The assignment to $umask is dead and can be removed.
Loading history...
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