RsaGenerator::sshEncodePublicKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 7
cp 0
crap 2
rs 10
c 0
b 0
f 0
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