Passed
Push — master ( 617e52...ff4e9f )
by Arthur
35:51
created

RsaGenerator::sshEncodePublicKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 7
ccs 6
cts 6
cp 1
crap 1
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 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);
0 ignored issues
show
Unused Code introduced by
The assignment to $umask is dead and can be removed.
Loading history...
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