Passed
Push — master ( 1ead19...82cb77 )
by Pierre
03:38
created

Pki   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

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