Passed
Push — master ( 463105...84cd59 )
by Roberto
04:47
created

PrivateKey::read()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 4
cts 5
cp 0.8
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 2.032
1
<?php
2
3
namespace NFePHP\Common\Certificate;
4
5
/**
6
 * Class for management and use of digital certificates A1 (PKCS # 12)
7
 * @category   NFePHP
8
 * @package    NFePHP\Common\ProvateKey
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 PrivateKey implements SignatureInterface
18
{
19
    /**
20
     * @var string
21
     */
22
    private $rawKey;
23
24
    /**
25
     * @var resource
26
     */
27
    private $resource;
28
29
    /**
30
     * PublicKey constructor.
31
     * @param string $privateKey Content of private key file
32
     */
33 5
    public function __construct($privateKey)
34
    {
35 5
        $this->rawKey = $privateKey;
36 5
        $this->read();
37 5
    }
38
39
    /**
40
     * Get a private key
41
     * @link http://php.net/manual/en/function.openssl-pkey-get-private.php
42
     * @return void
43
     * @throws CertificateException An error has occurred when get private key
44
     */
45 5
    protected function read()
46
    {
47 5
        if (!$resource = openssl_pkey_get_private($this->rawKey)) {
48
            throw CertificateException::getPrivateKey();
49
        }
50 5
        $this->resource = $resource;
51 5
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 4
    public function sign($content, $algorithm = OPENSSL_ALGO_SHA1)
57
    {
58 4
        $encryptedData = '';
59 4
        if (!openssl_sign($content, $encryptedData, $this->resource, $algorithm)) {
60
            throw CertificateException::signContent();
61
        }
62 4
        return $encryptedData;
63
    }
64
65
    public function __toString()
66
    {
67
        return $this->rawKey;
68
    }
69
}
70