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

Pki::validate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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