Completed
Pull Request — master (#15)
by
unknown
02:55
created

RsaDataSignature::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
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 nhuluc\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 Nhu Luc <[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