RsaDataSignature   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 55.56%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 66
ccs 10
cts 18
cp 0.5556
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 16 4
A generate() 0 10 3
A validate() 0 7 2
1
<?php
2
/**
3
 * @link https://github.com/yiiviet/yii2-payment
4
 * @copyright Copyright (c) 2017 Yii Viet
5
 * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
6
 */
7
8
namespace yiiviet\payment;
9
10
use yii\base\InvalidConfigException;
11
12
13
/**
14
 * Lớp RsaDataSignature dùng cho việc tạo và kiểm tra chữ ký theo chuẩn RSA.
15
 *
16
 * @author Vuong Minh <[email protected]>
17
 * @since 1.0
18
 */
19
class RsaDataSignature extends DataSignature
20
{
21
22
    /**
23
     * @var string Khóa dùng cho việc xác minh tính hợp lệ của dữ liệu thông qua chữ ký.
24
     */
25
    public $publicCertificate;
26
27
    /**
28
     * @var string Khóa dùng cho việc tạo chữ ký dữ liệu.
29
     */
30
    public $privateCertificate;
31
32
    /**
33
     * @var int Loại thuật toán openSSL. Ví dụ: OPENSSL_ALGO_MD5, OPENSSL_ALGO_SHA1...
34
     */
35
    public $openSSLAlgo;
36
37
    /**
38
     * @throws InvalidConfigException
39
     */
40 7
    public function init()
41
    {
42 7
        if ($this->openSSLAlgo === null) {
43
            throw new InvalidConfigException('Property `openSSLAlgo` must be set!');
44
        }
45
46 7
        if ($this->privateCertificate === null) {
47
            throw new InvalidConfigException('Property `privateCertificate` must be set for generate signature!');
48
        }
49
50 7
        if ($this->publicCertificate === null) {
51
            throw new InvalidConfigException('Property `publicCertificate` must be set for validate signature!');
52
        }
53
54 7
        parent::init();
55 7
    }
56
57
    /**
58
     * @inheritdoc
59
     * @throws InvalidConfigException
60
     */
61 7
    public function generate(): string
62
    {
63 7
        if (($privateKey = openssl_pkey_get_private($this->privateCertificate)) && openssl_sign($this->getData(), $signature, $privateKey, $this->openSSLAlgo)) {
64 7
            openssl_free_key($privateKey);
65
66 7
            return $signature;
67
        } else {
68
            throw new InvalidConfigException('Can not signature data via current private certificate!');
69
        }
70
    }
71
72
    /**
73
     * @inheritdoc
74
     * @throws InvalidConfigException
75
     */
76
    public function validate(string $expect): bool
77
    {
78
        $isValid = ($publicKey = openssl_pkey_get_public($this->publicCertificate)) && openssl_verify($this->getData(), $expect, $publicKey, $this->openSSLAlgo);
79
        openssl_free_key($publicKey);
80
81
        return $isValid;
82
    }
83
84
}
85