Completed
Pull Request — master (#46)
by Antonio Oertel
04:53
created

Base::pem2Der()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 1
eloc 7
nc 1
nop 1
crap 1
1
<?php
2
3
namespace NFePHP\Common\Certificate;
4
5
/**
6
 * Classe auxiliar para obter informações dos certificados digitais A1 (PKCS12)
7
 * Base para a classe ASN
8
 *
9
 * @category   NFePHP
10
 * @package    NFePHP\Common\Certificate
11
 * @copyright  Copyright (c) 2008-2014
12
 * @license    http://www.gnu.org/licenses/lesser.html LGPL v3
13
 * @author     Roberto L. Machado <linux.rlm at gmail dot com>
14
 * @link       http://github.com/nfephp-org/nfephp for the canonical source repository
15
 */
16
17
class Base
18
{
19
    /**
20
     * pem2Der
21
     * Transforma o certificado do formato PEM para o formato DER
22
     *
23
     * @param string $pem_data
0 ignored issues
show
Bug introduced by
There is no parameter named $pem_data. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
24
     * @return string
25
     */
26 4
    protected static function pem2Der($pemData)
27
    {
28 4
        $begin = "CERTIFICATE-----";
29 4
        $end = "-----END";
30
        //extrai o conteúdo do certificado entre as marcas BEGIN e END
31 4
        $pemData1 = substr($pemData, strpos($pemData, $begin) + strlen($begin));
32 4
        $pemData2 = substr($pemData1, 0, strpos($pemData1, $end));
33
        //converte o resultado para binário obtendo um certificado em formato DER
34 4
        $derData = base64_decode((string) $pemData2);
35 4
        return $derData;
36
    }
37
    
38
    /**
39
     * oidtoHex
40
     * Converte o numero de identificação do OID em uma representação asc,
41
     * coerente com o formato do certificado
42
     *
43
     * @param string $oid numero OID (com os pontos de separação)
44
     * @return string sequencia em hexadecimal
45
     */
46 4
    protected static function oidtoHex($oid)
47
    {
48 4
        if ($oid == '') {
49
            return '';
50
        }
51 4
        $abBinary = array();
52
        //coloca cada parte do numero do OID em uma linha da matriz
53 4
        $partes = explode('.', $oid);
54 4
        $bun = 0;
55
        //para cada numero compor o valor asc do mesmo
56 4
        for ($num = 0; $num < count($partes); $num++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
57 4
            if ($num == 0) {
58 4
                $bun = 40 * $partes[$num];
59 4
            } elseif ($num == 1) {
60 4
                $bun +=  $partes[$num];
61 4
                $abBinary[] = $bun;
62
            } else {
63 4
                $abBinary = self::xBase128((array) $abBinary, (integer) $partes[$num], true);
64
            }
65
        }
66 4
        $value = chr(0x06) . chr(count($abBinary));
67
        //para cada item da matriz compor a string de retorno como caracter
68 4
        foreach ($abBinary as $item) {
69 4
            $value .= chr($item);
70
        }
71 4
        return $value;
72
    }
73
74
    /**
75
     * xBase128
76
     * Retorna o dado convertido em asc
77
     *
78
     * @param array $abIn
79
     * @param integer $qIn
80
     * @param boolean $flag
81
     * @return integer
82
     */
83 4
    protected static function xBase128($abIn, $qIn, $flag)
84
    {
85 4
        $abc = $abIn;
86 4
        if ($qIn > 127) {
87
            $abc = self::xBase128($abc, floor($qIn/128), false);
88
        }
89 4
        $qIn2 = $qIn % 128;
90 4
        if ($flag) {
91 4
            $abc[] = $qIn2;
92
        } else {
93
            $abc[] = 0x80 | $qIn2;
94
        }
95 4
        return $abc;
96
    }
97
    
98
    /**
99
     * Retorna o valor em caracteres hexadecimais
100
     *
101
     * @param string $value
102
     * @return string
103
     * @return void
104
     */
105
    protected static function printHex($value)
106
    {
107
        $tabVal = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
108
        $hex = '';
109
        for ($i=0; $i<strlen($value); $i++) {
110
            $lsig = ord(substr($value, $i, 1)) % 16;
111
            $msig = (ord(substr($value, $i, 1)) - $lsig) / 16;
112
            $lessSig = $tabVal[$lsig];
113
            $moreSig = $tabVal[$msig];
114
            $hex .=  $moreSig.$lessSig;
115
        }
116
        return $hex;
117
    }
118
    
119
    /**
120
     * Obtêm o comprimento do conteúdo de uma sequência de dados do certificado
121
     *
122
     * @param integer $len variável passada por referência
123
     * @param integer $bytes variável passada por referência
124
     * @param string $data campo a
125
     * @return void
126
     */
127 4
    protected static function getLength(&$len, &$bytes, $data)
128
    {
129 4
        $len = ord($data[1]);
130 4
        $bytes = 0;
131
        // Testa se tamanho menor/igual a 127 bytes,
132
        // se for, então $len já é o tamanho do conteúdo
133 4
        if ($len & 0x80) {
134
            // Testa se tamanho indefinido (nao deve ocorrer em uma codificação DER)
135
            if ($len == chr(0x80)) {
136
                // Tamanho indefinido, limitado por 0x0000h
137
                $len = strpos($data, chr(0x00).chr(0x00));
138
                $bytes = 0;
139
            } else {
140
                //é tamanho definido. diz quantos bytes formam o tamanho
141
                $bytes = $len & 0x0f;
142
                $len = 0;
143
                for ($i = 0; $i < $bytes; $i++) {
144
                    $len = ($len << 8) | ord($data[$i + 2]);
145
                }
146
            }
147
        }
148 4
    }
149
}
150