Completed
Push — master ( 147d11...90c036 )
by Roberto
05:30 queued 02:17
created

PublicKey::read()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0058

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
ccs 13
cts 14
cp 0.9286
rs 9.2
cc 4
eloc 13
nc 5
nop 0
crap 4.0058
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 = $detail['issuer']['organizationalUnitName'];
99
        }
100 17
        $this->serialNumber = $detail['serialNumber'];
101 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...
102 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...
103 17
        $this->cnpj = Asn1::getCNPJ($this->unFormated());
104 17
    }
105
106
    /**
107
     * Verify signature
108
     * @link http://php.net/manual/en/function.openssl-verify.php
109
     * @param string $data
110
     * @param string $signature
111
     * @param int $algorithm [optional] For more information see the list of Signature Algorithms.
112
     * @return bool Returns true if the signature is correct, false if it is incorrect
113
     * @throws CertificateException An error has occurred when verify signature
114
     */
115 6
    public function verify($data, $signature, $algorithm = OPENSSL_ALGO_SHA1)
116
    {
117 6
        $verified = openssl_verify($data, $signature, $this->rawKey, $algorithm);
118 6
        if ($verified === self::SIGNATURE_ERROR) {
119
            throw CertificateException::signatureFailed();
120
        }
121 6
        return $verified === self::SIGNATURE_CORRECT;
122
    }
123
124
    /**
125
     * Check if is in valid date interval.
126
     * @return bool Returns true
127
     */
128 4
    public function isExpired()
129
    {
130 4
        return new \DateTime('now') > $this->validTo;
131
    }
132
133
    /**
134
     * Returns raw public key without markers and LF's
135
     * @return string
136
     */
137 17
    public function unFormated()
138
    {
139 17
        $ret = preg_replace('/-----.*[\n]?/', '', $this->rawKey);
140 17
        return preg_replace('/[\n\r]/', '', $ret);
141
    }
142
    
143
    /**
144
     * Returns raw public key
145
     * @return string
146
     */
147 1
    public function __toString()
148
    {
149 1
        return $this->rawKey;
150
    }
151
}
152