|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* LibreDTE |
|
5
|
|
|
* Copyright (C) SASCO SpA (https://sasco.cl) |
|
6
|
|
|
* |
|
7
|
|
|
* Este programa es software libre: usted puede redistribuirlo y/o |
|
8
|
|
|
* modificarlo bajo los términos de la Licencia Pública General Affero de GNU |
|
9
|
|
|
* publicada por la Fundación para el Software Libre, ya sea la versión |
|
10
|
|
|
* 3 de la Licencia, o (a su elección) cualquier versión posterior de la |
|
11
|
|
|
* misma. |
|
12
|
|
|
* |
|
13
|
|
|
* Este programa se distribuye con la esperanza de que sea útil, pero |
|
14
|
|
|
* SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita |
|
15
|
|
|
* MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO. |
|
16
|
|
|
* Consulte los detalles de la Licencia Pública General Affero de GNU para |
|
17
|
|
|
* obtener una información más detallada. |
|
18
|
|
|
* |
|
19
|
|
|
* Debería haber recibido una copia de la Licencia Pública General Affero de GNU |
|
20
|
|
|
* junto a este programa. |
|
21
|
|
|
* En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>. |
|
22
|
|
|
*/ |
|
23
|
|
|
|
|
24
|
|
|
namespace sasco\LibreDTE; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Clase para trabajar con firma electrónica, permite firmar y verificar firmas. |
|
28
|
|
|
* Provee los métodos: sign(), verify(), signXML() y verifyXML() |
|
29
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
30
|
|
|
* @version 2015-09-22 |
|
31
|
|
|
*/ |
|
32
|
|
|
class FirmaElectronica |
|
33
|
|
|
{ |
|
34
|
|
|
|
|
35
|
|
|
private $config; ///< Configuración de la firma electrónica |
|
36
|
|
|
private $certs; ///< Certificados digitales de la firma |
|
37
|
|
|
private $data; ///< Datos del certificado digial |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Constructor para la clase: crea configuración y carga certificado digital |
|
41
|
|
|
* |
|
42
|
|
|
* Si se desea pasar una configuración específica para la firma electrónica |
|
43
|
|
|
* se debe hacer a través de un arreglo con los índices file y pass, donde |
|
44
|
|
|
* file es la ruta hacia el archivo .p12 que contiene tanto la clave privada |
|
45
|
|
|
* como la pública y pass es la contraseña para abrir dicho archivo. |
|
46
|
|
|
* Ejemplo: |
|
47
|
|
|
* |
|
48
|
|
|
* \code{.php} |
|
49
|
|
|
* $firma_config = ['file'=>'/ruta/al/certificado.p12', 'pass'=>'contraseña']; |
|
50
|
|
|
* $firma = new \sasco\LibreDTE\FirmaElectronica($firma_config); |
|
51
|
|
|
* \endcode |
|
52
|
|
|
* |
|
53
|
|
|
* También se permite que en vez de pasar la ruta al certificado p12 se pase |
|
54
|
|
|
* el contenido del certificado, esto servirá por ejemplo si los datos del |
|
55
|
|
|
* archivo están almacenados en una base de datos. Ejemplo: |
|
56
|
|
|
* |
|
57
|
|
|
* \code{.php} |
|
58
|
|
|
* $firma_config = ['data'=>file_get_contents('/ruta/al/certificado.p12'), 'pass'=>'contraseña']; |
|
59
|
|
|
* $firma = new \sasco\LibreDTE\FirmaElectronica($firma_config); |
|
60
|
|
|
* \endcode |
|
61
|
|
|
* |
|
62
|
|
|
* @param config Configuración para la clase, si no se especifica se tratará de determinar |
|
63
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
64
|
|
|
* @version 2015-09-15 |
|
65
|
|
|
*/ |
|
66
|
|
|
public function __construct(array $config = []) |
|
67
|
|
|
{ |
|
68
|
|
|
// crear configuración |
|
69
|
|
|
if (!$config) { |
|
|
|
|
|
|
70
|
|
|
if (class_exists('\sowerphp\core\Configure')) { |
|
71
|
|
|
$config = (array)\sowerphp\core\Configure::read('firma_electronica.default'); |
|
72
|
|
|
} else { |
|
73
|
|
|
$config = []; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
$this->config = array_merge([ |
|
77
|
|
|
'file' => null, |
|
78
|
|
|
'pass' => null, |
|
79
|
|
|
'data' => null, |
|
80
|
|
|
'wordwrap' => 64, |
|
81
|
|
|
], $config); |
|
82
|
|
|
// cargar firma electrónica desde el contenido del archivo .p12 si no |
|
83
|
|
|
// se pasaron como datos del arreglo de configuración |
|
84
|
|
|
if (!$this->config['data'] and $this->config['file']) { |
|
|
|
|
|
|
85
|
|
|
if (is_readable($this->config['file'])) { |
|
86
|
|
|
$this->config['data'] = file_get_contents($this->config['file']); |
|
87
|
|
|
} else { |
|
88
|
|
|
return $this->error('Archivo de la firma electrónica '.basename($this->config['file']).' no puede ser leído'); |
|
|
|
|
|
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
// leer datos de la firma electrónica |
|
92
|
|
|
if ($this->config['data'] and openssl_pkcs12_read($this->config['data'], $this->certs, $this->config['pass'])===false) { |
|
|
|
|
|
|
93
|
|
|
return $this->error('No fue posible leer los datos de la firma electrónica (verificar la contraseña)'); |
|
|
|
|
|
|
94
|
|
|
} |
|
95
|
|
|
$this->data = openssl_x509_parse($this->certs['cert']); |
|
96
|
|
|
// quitar datos del contenido del archivo de la firma |
|
97
|
|
|
unset($this->config['data']); |
|
98
|
|
|
} |
|
99
|
|
|
|
|
100
|
|
|
/** |
|
101
|
|
|
* Método para generar un error usando una excepción de SowerPHP o terminar |
|
102
|
|
|
* el script si no se está usando el framework |
|
103
|
|
|
* @param msg Mensaje del error |
|
104
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
105
|
|
|
* @version 2017-08-04 |
|
106
|
|
|
*/ |
|
107
|
|
|
private function error($msg) |
|
108
|
|
|
{ |
|
109
|
|
|
if (class_exists('\sasco\LibreDTE\Estado') and class_exists('\sasco\LibreDTE\Log')) { |
|
|
|
|
|
|
110
|
|
|
$msg = \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FIRMA_ERROR, $msg); |
|
111
|
|
|
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::FIRMA_ERROR, $msg); |
|
|
|
|
|
|
112
|
|
|
return false; |
|
113
|
|
|
} else { |
|
114
|
|
|
throw new \Exception($msg); |
|
115
|
|
|
} |
|
116
|
|
|
} |
|
117
|
|
|
|
|
118
|
|
|
/** |
|
119
|
|
|
* Método que agrega el inicio y fin de un certificado (clave pública) |
|
120
|
|
|
* @param cert Certificado que se desea normalizar |
|
121
|
|
|
* @return Certificado con el inicio y fin correspondiente |
|
122
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
123
|
|
|
* @version 2015-08-20 |
|
124
|
|
|
*/ |
|
125
|
|
|
private function normalizeCert($cert) |
|
126
|
|
|
{ |
|
127
|
|
|
if (strpos($cert, '-----BEGIN CERTIFICATE-----')===false) { |
|
128
|
|
|
$body = trim($cert); |
|
129
|
|
|
$cert = '-----BEGIN CERTIFICATE-----'."\n"; |
|
130
|
|
|
$cert .= wordwrap($body, $this->config['wordwrap'], "\n", true)."\n"; |
|
131
|
|
|
$cert .= '-----END CERTIFICATE-----'."\n"; |
|
132
|
|
|
} |
|
133
|
|
|
return $cert; |
|
|
|
|
|
|
134
|
|
|
} |
|
135
|
|
|
|
|
136
|
|
|
/** |
|
137
|
|
|
* Método que entrega el RUN/RUT asociado al certificado |
|
138
|
|
|
* @return RUN/RUT asociado al certificado en formato: 11222333-4 |
|
|
|
|
|
|
139
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
140
|
|
|
* @version 2016-02-12 |
|
141
|
|
|
*/ |
|
142
|
|
|
public function getID() |
|
143
|
|
|
{ |
|
144
|
|
|
// RUN/RUT se encuentra en la extensión del certificado, esto de acuerdo |
|
145
|
|
|
// a Ley 19.799 sobre documentos electrónicos y firma electrónica |
|
146
|
|
|
$x509 = new \phpseclib\File\X509(); |
|
147
|
|
|
$cert = $x509->loadX509($this->certs['cert']); |
|
148
|
|
|
if (isset($cert['tbsCertificate']['extensions'])) { |
|
149
|
|
|
foreach ($cert['tbsCertificate']['extensions'] as $e) { |
|
150
|
|
|
if ($e['extnId']=='id-ce-subjectAltName') { |
|
151
|
|
|
return ltrim($e['extnValue'][0]['otherName']['value']['ia5String'], '0'); |
|
152
|
|
|
} |
|
153
|
|
|
} |
|
154
|
|
|
} |
|
155
|
|
|
// se obtiene desde serialNumber (esto es sólo para que funcione la firma para tests) |
|
156
|
|
|
if (isset($this->data['subject']['serialNumber'])) { |
|
157
|
|
|
return ltrim($this->data['subject']['serialNumber'], '0'); |
|
158
|
|
|
} |
|
159
|
|
|
// no se encontró el RUN |
|
160
|
|
|
return $this->error('No fue posible obtener el ID de la firma'); |
|
|
|
|
|
|
161
|
|
|
} |
|
162
|
|
|
|
|
163
|
|
|
/** |
|
164
|
|
|
* Método que entrega el CN del subject |
|
165
|
|
|
* @return CN del subject |
|
166
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
167
|
|
|
* @version 2016-02-12 |
|
168
|
|
|
*/ |
|
169
|
|
|
public function getName() |
|
170
|
|
|
{ |
|
171
|
|
|
if (isset($this->data['subject']['CN'])) |
|
172
|
|
|
return $this->data['subject']['CN']; |
|
173
|
|
|
return $this->error('No fue posible obtener el Name (subject.CN) de la firma'); |
|
|
|
|
|
|
174
|
|
|
} |
|
175
|
|
|
|
|
176
|
|
|
/** |
|
177
|
|
|
* Método que entrega el emailAddress del subject |
|
178
|
|
|
* @return emailAddress del subject |
|
179
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
180
|
|
|
* @version 2016-02-12 |
|
181
|
|
|
*/ |
|
182
|
|
|
public function getEmail() |
|
183
|
|
|
{ |
|
184
|
|
|
if (isset($this->data['subject']['emailAddress'])) |
|
185
|
|
|
return $this->data['subject']['emailAddress']; |
|
186
|
|
|
return $this->error('No fue posible obtener el Email (subject.emailAddress) de la firma'); |
|
|
|
|
|
|
187
|
|
|
} |
|
188
|
|
|
|
|
189
|
|
|
/** |
|
190
|
|
|
* Método que entrega desde cuando es válida la firma |
|
191
|
|
|
* @return validFrom_time_t |
|
192
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
193
|
|
|
* @version 2015-09-22 |
|
194
|
|
|
*/ |
|
195
|
|
|
public function getFrom() |
|
196
|
|
|
{ |
|
197
|
|
|
return date('Y-m-d H:i:s', $this->data['validFrom_time_t']); |
|
198
|
|
|
} |
|
199
|
|
|
|
|
200
|
|
|
/** |
|
201
|
|
|
* Método que entrega hasta cuando es válida la firma |
|
202
|
|
|
* @return validTo_time_t |
|
203
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
204
|
|
|
* @version 2015-09-22 |
|
205
|
|
|
*/ |
|
206
|
|
|
public function getTo() |
|
207
|
|
|
{ |
|
208
|
|
|
return date('Y-m-d H:i:s', $this->data['validTo_time_t']); |
|
209
|
|
|
} |
|
210
|
|
|
|
|
211
|
|
|
/** |
|
212
|
|
|
* Método que entrega el nombre del emisor de la firma |
|
213
|
|
|
* @return CN del issuer |
|
214
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
215
|
|
|
* @version 2015-09-22 |
|
216
|
|
|
*/ |
|
217
|
|
|
public function getIssuer() |
|
218
|
|
|
{ |
|
219
|
|
|
return $this->data['issuer']['CN']; |
|
220
|
|
|
} |
|
221
|
|
|
|
|
222
|
|
|
/** |
|
223
|
|
|
* Método que entrega los datos del certificado |
|
224
|
|
|
* @return Arreglo con todo los datos del certificado |
|
225
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
226
|
|
|
* @version 2015-09-11 |
|
227
|
|
|
*/ |
|
228
|
|
|
public function getData() |
|
229
|
|
|
{ |
|
230
|
|
|
return $this->data; |
|
231
|
|
|
} |
|
232
|
|
|
|
|
233
|
|
|
/** |
|
234
|
|
|
* Método que obtiene el módulo de la clave privada |
|
235
|
|
|
* @return Módulo en base64 |
|
236
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
237
|
|
|
* @version 2014-12-07 |
|
238
|
|
|
*/ |
|
239
|
|
|
public function getModulus() |
|
240
|
|
|
{ |
|
241
|
|
|
$details = openssl_pkey_get_details(openssl_pkey_get_private($this->certs['pkey'])); |
|
242
|
|
|
return wordwrap(base64_encode($details['rsa']['n']), $this->config['wordwrap'], "\n", true); |
|
243
|
|
|
} |
|
244
|
|
|
|
|
245
|
|
|
/** |
|
246
|
|
|
* Método que obtiene el exponente público de la clave privada |
|
247
|
|
|
* @return Exponente público en base64 |
|
248
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
249
|
|
|
* @version 2014-12-06 |
|
250
|
|
|
*/ |
|
251
|
|
|
public function getExponent() |
|
252
|
|
|
{ |
|
253
|
|
|
$details = openssl_pkey_get_details(openssl_pkey_get_private($this->certs['pkey'])); |
|
254
|
|
|
return wordwrap(base64_encode($details['rsa']['e']), $this->config['wordwrap'], "\n", true); |
|
255
|
|
|
} |
|
256
|
|
|
|
|
257
|
|
|
/** |
|
258
|
|
|
* Método que entrega el certificado de la firma |
|
259
|
|
|
* @return Contenido del certificado, clave pública del certificado digital, en base64 |
|
260
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
261
|
|
|
* @version 2015-08-24 |
|
262
|
|
|
*/ |
|
263
|
|
View Code Duplication |
public function getCertificate($clean = false) |
|
|
|
|
|
|
264
|
|
|
{ |
|
265
|
|
|
if ($clean) { |
|
266
|
|
|
return trim(str_replace( |
|
|
|
|
|
|
267
|
|
|
['-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----'], |
|
268
|
|
|
'', |
|
269
|
|
|
$this->certs['cert'] |
|
270
|
|
|
)); |
|
271
|
|
|
} else { |
|
272
|
|
|
return $this->certs['cert']; |
|
273
|
|
|
} |
|
274
|
|
|
} |
|
275
|
|
|
|
|
276
|
|
|
/** |
|
277
|
|
|
* Método que entrega la clave privada de la firma |
|
278
|
|
|
* @return Contenido de la clave privada del certificado digital en base64 |
|
279
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
280
|
|
|
* @version 2015-08-24 |
|
281
|
|
|
*/ |
|
282
|
|
View Code Duplication |
public function getPrivateKey($clean = false) |
|
|
|
|
|
|
283
|
|
|
{ |
|
284
|
|
|
if ($clean) { |
|
285
|
|
|
return trim(str_replace( |
|
|
|
|
|
|
286
|
|
|
['-----BEGIN PRIVATE KEY-----', '-----END PRIVATE KEY-----'], |
|
287
|
|
|
'', |
|
288
|
|
|
$this->certs['pkey'] |
|
289
|
|
|
)); |
|
290
|
|
|
} else { |
|
291
|
|
|
return $this->certs['pkey']; |
|
292
|
|
|
} |
|
293
|
|
|
} |
|
294
|
|
|
|
|
295
|
|
|
/** |
|
296
|
|
|
* Método para realizar la firma de datos |
|
297
|
|
|
* @param data Datos que se desean firmar |
|
298
|
|
|
* @param signature_alg Algoritmo que se utilizará para firmar (por defect SHA1) |
|
299
|
|
|
* @return Firma digital de los datos en base64 o =false si no se pudo firmar |
|
300
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
301
|
|
|
* @version 2014-12-08 |
|
302
|
|
|
*/ |
|
303
|
|
|
public function sign($data, $signature_alg = OPENSSL_ALGO_SHA1) |
|
304
|
|
|
{ |
|
305
|
|
|
$signature = null; |
|
306
|
|
|
if (openssl_sign($data, $signature, $this->certs['pkey'], $signature_alg)==false) { |
|
|
|
|
|
|
307
|
|
|
return $this->error('No fue posible firmar los datos'); |
|
|
|
|
|
|
308
|
|
|
} |
|
309
|
|
|
return base64_encode($signature); |
|
310
|
|
|
} |
|
311
|
|
|
|
|
312
|
|
|
/** |
|
313
|
|
|
* Método que verifica la firma digital de datos |
|
314
|
|
|
* @param data Datos que se desean verificar |
|
315
|
|
|
* @param signature Firma digital de los datos en base64 |
|
316
|
|
|
* @param pub_key Certificado digital, clave pública, de la firma |
|
317
|
|
|
* @param signature_alg Algoritmo que se usó para firmar (por defect SHA1) |
|
318
|
|
|
* @return =true si la firma está ok, =false si está mal o no se pudo determinar |
|
|
|
|
|
|
319
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
320
|
|
|
* @version 2014-12-08 |
|
321
|
|
|
*/ |
|
322
|
|
|
public function verify($data, $signature, $pub_key = null, $signature_alg = OPENSSL_ALGO_SHA1) |
|
323
|
|
|
{ |
|
324
|
|
|
if ($pub_key === null) |
|
325
|
|
|
$pub_key = $this->certs['cert']; |
|
326
|
|
|
$pub_key = $this->normalizeCert($pub_key); |
|
327
|
|
|
return openssl_verify($data, base64_decode($signature), $pub_key, $signature_alg) == 1 ? true : false; |
|
328
|
|
|
} |
|
329
|
|
|
|
|
330
|
|
|
/** |
|
331
|
|
|
* Método que firma un XML utilizando RSA y SHA1 |
|
332
|
|
|
* |
|
333
|
|
|
* Referencia: http://www.di-mgt.com.au/xmldsig2.html |
|
334
|
|
|
* |
|
335
|
|
|
* @param xml Datos XML que se desean firmar |
|
336
|
|
|
* @param reference Referencia a la que hace la firma |
|
337
|
|
|
* @return XML firmado o =false si no se pudo fimar |
|
338
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
339
|
|
|
* @version 2017-10-22 |
|
340
|
|
|
*/ |
|
341
|
|
|
public function signXML($xml, $reference = '', $tag = null, $xmlns_xsi = false) |
|
342
|
|
|
{ |
|
343
|
|
|
// normalizar 4to parámetro que puede ser boolean o array |
|
344
|
|
|
if (is_array($xmlns_xsi)) { |
|
345
|
|
|
$namespace = $xmlns_xsi; |
|
346
|
|
|
$xmlns_xsi = false; |
|
347
|
|
|
} else { |
|
348
|
|
|
$namespace = null; |
|
349
|
|
|
} |
|
350
|
|
|
// obtener objeto del XML que se va a firmar |
|
351
|
|
|
$doc = new XML(); |
|
352
|
|
|
$doc->loadXML($xml); |
|
353
|
|
|
if (!$doc->documentElement) { |
|
354
|
|
|
return $this->error('No se pudo obtener el documentElement desde el XML a firmar (posible XML mal formado)'); |
|
|
|
|
|
|
355
|
|
|
} |
|
356
|
|
|
// crear nodo para la firma |
|
357
|
|
|
$Signature = $doc->importNode((new XML())->generate([ |
|
358
|
|
|
'Signature' => [ |
|
359
|
|
|
'@attributes' => $namespace ? false : [ |
|
360
|
|
|
'xmlns' => 'http://www.w3.org/2000/09/xmldsig#', |
|
361
|
|
|
], |
|
362
|
|
|
'SignedInfo' => [ |
|
363
|
|
|
'@attributes' => $namespace ? false : [ |
|
364
|
|
|
'xmlns' => 'http://www.w3.org/2000/09/xmldsig#', |
|
365
|
|
|
'xmlns:xsi' => $xmlns_xsi ? 'http://www.w3.org/2001/XMLSchema-instance' : false, |
|
366
|
|
|
], |
|
367
|
|
|
'CanonicalizationMethod' => [ |
|
368
|
|
|
'@attributes' => [ |
|
369
|
|
|
'Algorithm' => 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315', |
|
370
|
|
|
], |
|
371
|
|
|
], |
|
372
|
|
|
'SignatureMethod' => [ |
|
373
|
|
|
'@attributes' => [ |
|
374
|
|
|
'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1', |
|
375
|
|
|
], |
|
376
|
|
|
], |
|
377
|
|
|
'Reference' => [ |
|
378
|
|
|
'@attributes' => [ |
|
379
|
|
|
'URI' => $reference, |
|
380
|
|
|
], |
|
381
|
|
|
'Transforms' => [ |
|
382
|
|
|
'Transform' => [ |
|
383
|
|
|
'@attributes' => [ |
|
384
|
|
|
'Algorithm' => $namespace ? 'http://www.altova.com' : 'http://www.w3.org/2000/09/xmldsig#enveloped-signature', |
|
385
|
|
|
], |
|
386
|
|
|
], |
|
387
|
|
|
], |
|
388
|
|
|
'DigestMethod' => [ |
|
389
|
|
|
'@attributes' => [ |
|
390
|
|
|
'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#sha1', |
|
391
|
|
|
], |
|
392
|
|
|
], |
|
393
|
|
|
'DigestValue' => null, |
|
394
|
|
|
], |
|
395
|
|
|
], |
|
396
|
|
|
'SignatureValue' => null, |
|
397
|
|
|
'KeyInfo' => [ |
|
398
|
|
|
'KeyValue' => [ |
|
399
|
|
|
'RSAKeyValue' => [ |
|
400
|
|
|
'Modulus' => null, |
|
401
|
|
|
'Exponent' => null, |
|
402
|
|
|
], |
|
403
|
|
|
], |
|
404
|
|
|
'X509Data' => [ |
|
405
|
|
|
'X509Certificate' => null, |
|
406
|
|
|
], |
|
407
|
|
|
], |
|
408
|
|
|
], |
|
409
|
|
|
], $namespace)->documentElement, true); |
|
410
|
|
|
// calcular DigestValue |
|
411
|
|
|
if ($tag) { |
|
412
|
|
|
$item = $doc->documentElement->getElementsByTagName($tag)->item(0); |
|
413
|
|
|
if (!$item) { |
|
414
|
|
|
return $this->error('No fue posible obtener el nodo con el tag '.$tag); |
|
|
|
|
|
|
415
|
|
|
} |
|
416
|
|
|
$digest = base64_encode(sha1($item->C14N(), true)); |
|
417
|
|
|
} else { |
|
418
|
|
|
$digest = base64_encode(sha1($doc->C14N(), true)); |
|
419
|
|
|
} |
|
420
|
|
|
$Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue = $digest; |
|
421
|
|
|
// calcular SignatureValue |
|
422
|
|
|
$SignedInfo = $doc->saveHTML($Signature->getElementsByTagName('SignedInfo')->item(0)); |
|
423
|
|
|
$firma = $this->sign($SignedInfo); |
|
|
|
|
|
|
424
|
|
|
if (!$firma) |
|
425
|
|
|
return false; |
|
426
|
|
|
$signature = wordwrap($firma, $this->config['wordwrap'], "\n", true); |
|
427
|
|
|
// reemplazar valores en la firma de |
|
428
|
|
|
$Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue = $signature; |
|
429
|
|
|
$Signature->getElementsByTagName('Modulus')->item(0)->nodeValue = $this->getModulus(); |
|
430
|
|
|
$Signature->getElementsByTagName('Exponent')->item(0)->nodeValue = $this->getExponent(); |
|
431
|
|
|
$Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue = $this->getCertificate(true); |
|
432
|
|
|
// agregar y entregar firma |
|
433
|
|
|
$doc->documentElement->appendChild($Signature); |
|
434
|
|
|
return $doc->saveXML(); |
|
435
|
|
|
} |
|
436
|
|
|
|
|
437
|
|
|
/** |
|
438
|
|
|
* Método que verifica la validez de la firma de un XML utilizando RSA y SHA1 |
|
439
|
|
|
* @param xml_data Archivo XML que se desea validar |
|
440
|
|
|
* @return =true si la firma del documento XML es válida o =false si no lo es |
|
|
|
|
|
|
441
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
442
|
|
|
* @version 2015-09-02 |
|
443
|
|
|
*/ |
|
444
|
|
|
public function verifyXML($xml_data, $tag = null) |
|
445
|
|
|
{ |
|
446
|
|
|
$doc = new XML(); |
|
447
|
|
|
$doc->loadXML($xml_data); |
|
448
|
|
|
// preparar datos que se verificarán |
|
449
|
|
|
$SignaturesElements = $doc->documentElement->getElementsByTagName('Signature'); |
|
450
|
|
|
$Signature = $doc->documentElement->removeChild($SignaturesElements->item($SignaturesElements->length-1)); |
|
451
|
|
|
$SignedInfo = $Signature->getElementsByTagName('SignedInfo')->item(0); |
|
452
|
|
|
$SignedInfo->setAttribute('xmlns', $Signature->getAttribute('xmlns')); |
|
453
|
|
|
$signed_info = $doc->saveHTML($SignedInfo); |
|
454
|
|
|
$signature = $Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue; |
|
455
|
|
|
$pub_key = $Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue; |
|
456
|
|
|
// verificar firma |
|
457
|
|
|
if (!$this->verify($signed_info, $signature, $pub_key)) |
|
|
|
|
|
|
458
|
|
|
return false; |
|
459
|
|
|
// verificar digest |
|
460
|
|
|
$digest_original = $Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue; |
|
461
|
|
|
if ($tag) { |
|
462
|
|
|
$digest_calculado = base64_encode(sha1($doc->documentElement->getElementsByTagName($tag)->item(0)->C14N(), true)); |
|
463
|
|
|
} else { |
|
464
|
|
|
$digest_calculado = base64_encode(sha1($doc->C14N(), true)); |
|
465
|
|
|
} |
|
466
|
|
|
return $digest_original == $digest_calculado; |
|
467
|
|
|
} |
|
468
|
|
|
|
|
469
|
|
|
/** |
|
470
|
|
|
* Método que obtiene la clave asociada al módulo y exponente entregados |
|
471
|
|
|
* @param modulus Módulo de la clave |
|
472
|
|
|
* @param exponent Exponente de la clave |
|
473
|
|
|
* @return Entrega la clave asociada al módulo y exponente |
|
474
|
|
|
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) |
|
475
|
|
|
* @version 2015-09-19 |
|
476
|
|
|
*/ |
|
477
|
|
|
public static function getFromModulusExponent($modulus, $exponent) |
|
478
|
|
|
{ |
|
479
|
|
|
$rsa = new \phpseclib\Crypt\RSA(); |
|
480
|
|
|
$modulus = new \phpseclib\Math\BigInteger(base64_decode($modulus), 256); |
|
481
|
|
|
$exponent = new \phpseclib\Math\BigInteger(base64_decode($exponent), 256); |
|
482
|
|
|
$rsa->loadKey(['n' => $modulus, 'e' => $exponent]); |
|
483
|
|
|
$rsa->setPublicKey(); |
|
484
|
|
|
return $rsa->getPublicKey(); |
|
485
|
|
|
} |
|
486
|
|
|
|
|
487
|
|
|
} |
|
488
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.