Completed
Pull Request — master (#135)
by Eduardo
04:38
created

PublicKey::read()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5.0488

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 20
ccs 14
cts 16
cp 0.875
rs 8.8571
cc 5
eloc 15
nc 7
nop 0
crap 5.0488
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 string
29
     */
30
    public $cnpj;
31
    /**
32
     * @var \DateTime
33
     */
34
    public $validFrom;
35
    /**
36
     * @var \DateTime
37
     */
38
    public $validTo;
39
    /**
40
     * @var string
41
     */
42
    public $emailAddress;
43
    /**
44
     * @var string Cryptographic Service Provider
45
     */
46
    public $cspName;
47
    /**
48
     * @var string
49
     */
50
    public $serialNumber;
51
52
    /**
53
     * PublicKey constructor.
54
     * @param string $publicKey
55
     */
56 17
    public function __construct($publicKey)
57
    {
58 17
        $this->rawKey = $publicKey;
59 17
        $this->read();
60 17
    }
61
    
62
    /**
63
     * Load class with certificate content
64
     * @param string $content
65
     * @return \static
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 17
    protected function read()
88
    {
89 17
        if (!$resource = openssl_x509_read($this->rawKey)) {
90
            throw CertificateException::unableToOpen();
91
        }
92 17
        $detail = openssl_x509_parse($resource, false);
93 17
        $this->commonName = $detail['subject']['commonName'];
94 17
        if (isset($detail['subject']['emailAddress'])) {
95 1
            $this->emailAddress = $detail['subject']['emailAddress'];
96
        }
97 17
        if (isset($detail['issuer']['organizationalUnitName'])) {
98 17
            $this->cspName = is_array($detail['issuer']['organizationalUnitName'])
99
                ? implode(', ', $detail['issuer']['organizationalUnitName'])
100 17
                : $detail['issuer']['organizationalUnitName'];
101
        }
102 17
        $this->serialNumber = $detail['serialNumber'];
103 17
        $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 17
        $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 17
        $this->cnpj = Asn1::getCNPJ($this->unFormated());
106 17
    }
107
108
    /**
109
     * Verify signature
110
     * @link http://php.net/manual/en/function.openssl-verify.php
111
     * @param string $data
112
     * @param string $signature
113
     * @param int $algorithm [optional] For more information see the list of Signature Algorithms.
114
     * @return bool Returns true if the signature is correct, false if it is incorrect
115
     * @throws CertificateException An error has occurred when verify signature
116
     */
117 6
    public function verify($data, $signature, $algorithm = OPENSSL_ALGO_SHA1)
118
    {
119 6
        $verified = openssl_verify($data, $signature, $this->rawKey, $algorithm);
120 6
        if ($verified === self::SIGNATURE_ERROR) {
121
            throw CertificateException::signatureFailed();
122
        }
123 6
        return $verified === self::SIGNATURE_CORRECT;
124
    }
125
126
    /**
127
     * Check if is in valid date interval.
128
     * @return bool Returns true
129
     */
130 4
    public function isExpired()
131
    {
132 4
        return new \DateTime('now') > $this->validTo;
133
    }
134
135
    /**
136
     * Returns raw public key without markers and LF's
137
     * @return string
138
     */
139 17
    public function unFormated()
140
    {
141 17
        $ret = preg_replace('/-----.*[\n]?/', '', $this->rawKey);
142 17
        return preg_replace('/[\n\r]/', '', $ret);
143
    }
144
    
145
    /**
146
     * Returns raw public key
147
     * @return string
148
     */
149 1
    public function __toString()
150
    {
151 1
        return $this->rawKey;
152
    }
153
}
154