Pki   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 73
ccs 16
cts 16
cp 1
rs 10
wmc 5

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A decrypt() 0 4 1
A generateKeyPair() 0 8 1
A validate() 0 3 1
A encrypt() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Component;
6
7
use Nymfonya\Component\Container;
8
9
class Pki
10
{
11
12
    /**
13
     * container
14
     *
15
     * @var Container
16
     */
17
    private $container;
18
19
    /**
20
     * instanciate
21
     *
22
     * @param Container $container
23
     */
24 4
    public function __construct(Container $container)
25
    {
26 4
        $this->container = $container;
27
    }
28
29
    /**
30
     * generate an return array of private and public key
31
     *
32
     * @return array
33
     */
34 3
    public function generateKeyPair(): array
35
    {
36 3
        $res = openssl_pkey_new([
37 3
            'private_key_bits' => 2048,
38 3
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
39
        ]);
40 3
        openssl_pkey_export($res, $privKey);
41 3
        return [$privKey, openssl_pkey_get_details($res)['key']];
42
    }
43
44
    /**
45
     * encrypt a message with private key
46
     *
47
     * @param string $message
48
     * @param string $privKey
49
     * @return string
50
     */
51 2
    public function encrypt(string $message, string $privKey): string
52
    {
53 2
        openssl_private_encrypt($message, $crypted, $privKey);
54 2
        return base64_encode($crypted);
55
    }
56
57
58
    /**
59
     * decrypt a message with public key
60
     *
61
     * @param string $message
62
     * @param string $pubKey
63
     * @return string
64
     */
65 2
    public function decrypt(string $message, string $pubKey): string
66
    {
67 2
        openssl_public_decrypt(base64_decode($message), $decrypted, $pubKey);
68 2
        return $decrypted;
69
    }
70
71
    /**
72
     * return true if message match crypted with a public key
73
     *
74
     * @param string $message
75
     * @param string $crypted
76
     * @param string $pubKey
77
     * @return boolean
78
     */
79 1
    public function validate(string $message, string $crypted, string $pubKey): bool
80
    {
81 1
        return $message == $this->decrypt($crypted, $pubKey);
82
    }
83
}
84