Passed
Pull Request — master (#215)
by Bill
02:12
created

PublicKey::read()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6.031

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 19
cts 21
cp 0.9048
rs 8.8817
c 0
b 0
f 0
cc 6
nc 13
nop 0
crap 6.031
1
<?php
2
3
namespace NFePHP\Common\Certificate;
4
5
/**
6
 * Management and use of digital certificates A1 (PKCS # 12).
7
 * @category   NFePHP
8
 * @package    NFePHP\Common\PublicKey
9
 * @copyright  Copyright (c) 2008-2016
10
 * @license    http://www.gnu.org/licenses/lesser.html LGPL v3
11
 * @author     Antonio Spinelli <tonicospinelli85 at gmail dot com>
12
 * @link       http://github.com/nfephp-org/sped-common for the canonical source repository
13
 */
14
15
use NFePHP\Common\Exception\CertificateException;
16
17
class PublicKey implements VerificationInterface
18
{
19
    /**
20
     * @var string
21
     */
22
    private $rawKey;
23
    /**
24
     * @var string
25
     */
26
    public $commonName;
27
    /**
28
     * @var \DateTime
29
     */
30
    public $validFrom;
31
    /**
32
     * @var \DateTime
33
     */
34
    public $validTo;
35
    /**
36
     * @var string
37
     */
38
    public $emailAddress;
39
    /**
40
     * @var string Cryptographic Service Provider
41
     */
42
    public $cspName;
43
    /**
44
     * @var string
45
     */
46
    public $serialNumber;
47
    /**
48
     * @var string
49
     */
50
    public $subjectNameValue;
51
52
    /**
53
     * PublicKey constructor.
54
     * @param string $publicKey
55
     */
56 19
    public function __construct($publicKey)
57
    {
58 19
        $this->rawKey = $publicKey;
59 19
        $this->read();
60 19
    }
61
    
62
    /**
63
     * Load class with certificate content
64
     * @param string $content
65
     * @return \NFePHP\Common\Certificate\PublicKey
66
     */
67 5
    public static function createFromContent($content)
68
    {
69 5
        $content = rtrim(chunk_split(preg_replace('/[\r\n]/', '', $content), 64, PHP_EOL));
70
        $certificate = <<<CONTENT
71
-----BEGIN CERTIFICATE-----
72 5
{$content}
73
-----END CERTIFICATE-----
74
75
CONTENT;
76
77 5
        return new static($certificate);
78
    }
79
    
80
    /**
81
     * Parse an X509 certificate and define the information in object
82
     * @link http://php.net/manual/en/function.openssl-x509-read.php
83
     * @link http://php.net/manual/en/function.openssl-x509-parse.php
84
     * @return void
85
     * @throws CertificateException Unable to open certificate
86
     */
87 19
    protected function read()
88
    {
89 19
        if (!$resource = openssl_x509_read($this->rawKey)) {
90
            throw CertificateException::unableToOpen();
91
        }
92 19
        $detail = openssl_x509_parse($resource, false);
93 19
        $this->commonName = $detail['subject']['commonName'];
94 19
        if (isset($detail['subject']['emailAddress'])) {
95 1
            $this->emailAddress = $detail['subject']['emailAddress'];
96
        }
97 19
        if (isset($detail['issuer']['organizationalUnitName'])) {
98 19
            $this->cspName = is_array($detail['issuer']['organizationalUnitName'])
99
                ? implode(', ', $detail['issuer']['organizationalUnitName'])
100 19
                : $detail['issuer']['organizationalUnitName'];
101
        }
102 19
        $this->serialNumber = $detail['serialNumber'];
103 19
        $this->validFrom = \DateTime::createFromFormat('ymdHis\Z', $detail['validFrom']);
0 ignored issues
show
Documentation Bug introduced by
It seems like \DateTime::createFromFor..., $detail['validFrom']) can also be of type false. However, the property $validFrom is declared as type object<DateTime>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
104 19
        $this->validTo = \DateTime::createFromFormat('ymdHis\Z', $detail['validTo']);
0 ignored issues
show
Documentation Bug introduced by
It seems like \DateTime::createFromFor...Z', $detail['validTo']) can also be of type false. However, the property $validTo is declared as type object<DateTime>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
105 19
        if (isset($detail['name'])) {
106 19
            $arrayName = explode("/",$detail["name"]);
107 19
            $arrayName = array_reverse($arrayName);
108 19
            $arrayName = array_filter($arrayName);
109 19
            $name = implode(",",$arrayName);
110 19
            $this->subjectNameValue = $name;
111
        }
112 19
    }
113
114
    /**
115
     * Verify signature
116
     * @link http://php.net/manual/en/function.openssl-verify.php
117
     * @param string $data
118
     * @param string $signature
119
     * @param int $algorithm [optional] For more information see the list of Signature Algorithms.
120
     * @return bool Returns true if the signature is correct, false if it is incorrect
121
     * @throws CertificateException An error has occurred when verify signature
122
     */
123 6
    public function verify($data, $signature, $algorithm = OPENSSL_ALGO_SHA1)
124
    {
125 6
        $verified = openssl_verify($data, $signature, $this->rawKey, $algorithm);
126 6
        if ($verified === self::SIGNATURE_ERROR) {
127
            throw CertificateException::signatureFailed();
128
        }
129 6
        return $verified === self::SIGNATURE_CORRECT;
130
    }
131
132
    /**
133
     * Check if is in valid date interval.
134
     * @return bool Returns true
135
     */
136 4
    public function isExpired()
137
    {
138 4
        return new \DateTime('now') > $this->validTo;
139
    }
140
141
    /**
142
     * Returns raw public key without markers and LF's
143
     * @return string
144
     */
145 5
    public function unFormated()
146
    {
147 5
        $ret = preg_replace('/-----.*[\n]?/', '', $this->rawKey);
148 5
        return preg_replace('/[\n\r]/', '', $ret);
149
    }
150
    
151
    /**
152
     * Returns raw public key
153
     * @return string
154
     */
155 1
    public function __toString()
156
    {
157 1
        return $this->rawKey;
158
    }
159
    
160
    /**
161
     * Extract CNPJ number by OID
162
     * @return string
163
     */
164 1
    public function cnpj()
165
    {
166 1
        return Asn1::getCNPJ($this->unFormated());
167
    }
168
169
    /**
170
     * Extract CPF number by OID
171
     * @return string
172
     */
173 2
    public function cpf()
174
    {
175 2
        return Asn1::getCPF($this->unFormated());
176
    }
177
}
178