-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathXMLSecurityKey.php
More file actions
484 lines (440 loc) · 18.9 KB
/
XMLSecurityKey.php
File metadata and controls
484 lines (440 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
<?php
class XMLSecurityKey
{
const TRIPLEDES_CBC = 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc';
const AES128_CBC = 'http://www.w3.org/2001/04/xmlenc#aes128-cbc';
const AES192_CBC = 'http://www.w3.org/2001/04/xmlenc#aes192-cbc';
const AES256_CBC = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc';
const RSA_1_5 = 'http://www.w3.org/2001/04/xmlenc#rsa-1_5';
const RSA_OAEP_MGF1P = 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p';
const DSA_SHA1 = 'http://www.w3.org/2000/09/xmldsig#dsa-sha1';
const RSA_SHA1 = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
const RSA_SHA256 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
const RSA_SHA384 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384';
const RSA_SHA512 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512';
private $cryptParams = array();
public $type = 0;
public $key = NULL;
public $passphrase = "";
public $iv = NULL;
public $name = NULL;
public $keyChain = NULL;
public $isEncrypted = FALSE;
public $encryptedCtx = NULL;
public $guid = NULL;
/**
* This variable contains the certificate as a string if this key represents an X509-certificate.
* If this key doesn't represent a certificate, this will be NULL.
*/
private $x509Certificate = NULL;
/* This variable contains the certificate thunbprint if we have loaded an X509-certificate. */
private $X509Thumbprint = NULL;
public function __construct($type, $params=NULL) {
srand();
switch ($type) {
case (XMLSecurityKey::TRIPLEDES_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_TRIPLEDES;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc';
$this->cryptParams['keysize'] = 24;
break;
case (XMLSecurityKey::AES128_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes128-cbc';
$this->cryptParams['keysize'] = 16;
break;
case (XMLSecurityKey::AES192_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes192-cbc';
$this->cryptParams['keysize'] = 24;
break;
case (XMLSecurityKey::AES256_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc';
$this->cryptParams['keysize'] = 32;
break;
case (XMLSecurityKey::RSA_1_5):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#rsa-1_5';
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
return;
case (XMLSecurityKey::RSA_OAEP_MGF1P):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['padding'] = OPENSSL_PKCS1_OAEP_PADDING;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p';
$this->cryptParams['hash'] = NULL;
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
return;
case (XMLSecurityKey::RSA_SHA1):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
break;
case (XMLSecurityKey::RSA_SHA256):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['digest'] = 'SHA256';
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
break;
case (XMLSecurityKey::RSA_SHA384):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['digest'] = 'SHA384';
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
case (XMLSecurityKey::RSA_SHA512):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['digest'] = 'SHA512';
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
default:
throw new Exception('Invalid Key Type');
return;
}
$this->type = $type;
}
/**
* Retrieve the key size for the symmetric encryption algorithm..
*
* If the key size is unknown, or this isn't a symmetric encryption algorithm,
* NULL is returned.
*
* @return int|NULL The number of bytes in the key.
*/
public function getSymmetricKeySize() {
if (! isset($this->cryptParams['keysize'])) {
return NULL;
}
return $this->cryptParams['keysize'];
}
public function generateSessionKey() {
if (!isset($this->cryptParams['keysize'])) {
throw new Exception('Unknown key size for type "' . $this->type . '".');
}
$keysize = $this->cryptParams['keysize'];
if (function_exists('openssl_random_pseudo_bytes')) {
/* We have PHP >= 5.3 - use openssl to generate session key. */
$key = openssl_random_pseudo_bytes($keysize);
} else {
/* Generating random key using iv generation routines */
$key = mcrypt_create_iv($keysize, MCRYPT_RAND);
}
if ($this->type === XMLSecurityKey::TRIPLEDES_CBC) {
/* Make sure that the generated key has the proper parity bits set.
* Mcrypt doesn't care about the parity bits, but others may care.
*/
for ($i = 0; $i < strlen($key); $i++) {
$byte = ord($key[$i]) & 0xfe;
$parity = 1;
for ($j = 1; $j < 8; $j++) {
$parity ^= ($byte >> $j) & 1;
}
$byte |= $parity;
$key[$i] = chr($byte);
}
}
$this->key = $key;
return $key;
}
public static function getRawThumbprint($cert) {
$arCert = explode("\n", $cert);
$data = '';
$inData = FALSE;
foreach ($arCert AS $curData) {
if (! $inData) {
if (strncmp($curData, '-----BEGIN CERTIFICATE', 22) == 0) {
$inData = TRUE;
}
} else {
if (strncmp($curData, '-----END CERTIFICATE', 20) == 0) {
$inData = FALSE;
break;
}
$data .= trim($curData);
}
}
if (! empty($data)) {
return strtolower(sha1(base64_decode($data)));
}
return NULL;
}
public function loadKey($key, $isFile=FALSE, $isCert = FALSE) {
if ($isFile) {
$this->key = file_get_contents($key);
} else {
$this->key = $key;
}
if ($isCert) {
$this->key = openssl_x509_read($this->key);
openssl_x509_export($this->key, $str_cert);
$this->x509Certificate = $str_cert;
$this->key = $str_cert;
} else {
$this->x509Certificate = NULL;
}
if ($this->cryptParams['library'] == 'openssl') {
if ($this->cryptParams['type'] == 'public') {
if ($isCert) {
/* Load the thumbprint if this is an X509 certificate. */
$this->X509Thumbprint = self::getRawThumbprint($this->key);
}
$this->key = openssl_get_publickey($this->key);
} else {
$this->key = openssl_get_privatekey($this->key, $this->passphrase);
}
} else if ($this->cryptParams['cipher'] == MCRYPT_RIJNDAEL_128) {
/* Check key length */
switch ($this->type) {
case (XMLSecurityKey::AES256_CBC):
if (strlen($this->key) < 25) {
throw new Exception('Key must contain at least 25 characters for this cipher');
}
break;
case (XMLSecurityKey::AES192_CBC):
if (strlen($this->key) < 17) {
throw new Exception('Key must contain at least 17 characters for this cipher');
}
break;
}
}
}
private function encryptMcrypt($data) {
$td = mcrypt_module_open($this->cryptParams['cipher'], '', $this->cryptParams['mode'], '');
$this->iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $this->key, $this->iv);
if ($this->cryptParams['mode'] == MCRYPT_MODE_CBC) {
$bs = mcrypt_enc_get_block_size($td);
for ($datalen0=$datalen=strlen($data); (($datalen%$bs)!=($bs-1)); $datalen++)
$data.=chr(rand(1, 127));
$data.=chr($datalen-$datalen0+1);
}
$encrypted_data = $this->iv.mcrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $encrypted_data;
}
private function decryptMcrypt($data) {
$td = mcrypt_module_open($this->cryptParams['cipher'], '', $this->cryptParams['mode'], '');
$iv_length = mcrypt_enc_get_iv_size($td);
$this->iv = substr($data, 0, $iv_length);
$data = substr($data, $iv_length);
mcrypt_generic_init($td, $this->key, $this->iv);
$decrypted_data = mdecrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
if ($this->cryptParams['mode'] == MCRYPT_MODE_CBC) {
$dataLen = strlen($decrypted_data);
$paddingLength = substr($decrypted_data, $dataLen - 1, 1);
$decrypted_data = substr($decrypted_data, 0, $dataLen - ord($paddingLength));
}
return $decrypted_data;
}
private function encryptOpenSSL($data) {
if ($this->cryptParams['type'] == 'public') {
if (! openssl_public_encrypt($data, $encrypted_data, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure encrypting Data');
return;
}
} else {
if (! openssl_private_encrypt($data, $encrypted_data, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure encrypting Data');
return;
}
}
return $encrypted_data;
}
private function decryptOpenSSL($data) {
if ($this->cryptParams['type'] == 'public') {
if (! openssl_public_decrypt($data, $decrypted, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure decrypting Data');
return;
}
} else {
if (! openssl_private_decrypt($data, $decrypted, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure decrypting Data');
return;
}
}
return $decrypted;
}
private function signOpenSSL($data) {
$algo = OPENSSL_ALGO_SHA1;
if (! empty($this->cryptParams['digest'])) {
$algo = $this->cryptParams['digest'];
}
if (! openssl_sign ($data, $signature, $this->key, $algo)) {
throw new Exception('Failure Signing Data: ' . openssl_error_string() . ' - ' . $algo);
return;
}
return $signature;
}
private function verifyOpenSSL($data, $signature) {
$algo = OPENSSL_ALGO_SHA1;
if (! empty($this->cryptParams['digest'])) {
$algo = $this->cryptParams['digest'];
}
return openssl_verify ($data, $signature, $this->key, $algo);
}
public function encryptData($data) {
switch ($this->cryptParams['library']) {
case 'mcrypt':
return $this->encryptMcrypt($data);
break;
case 'openssl':
return $this->encryptOpenSSL($data);
break;
}
}
public function decryptData($data) {
switch ($this->cryptParams['library']) {
case 'mcrypt':
return $this->decryptMcrypt($data);
break;
case 'openssl':
return $this->decryptOpenSSL($data);
break;
}
}
public function signData($data) {
switch ($this->cryptParams['library']) {
case 'openssl':
return $this->signOpenSSL($data);
break;
}
}
public function verifySignature($data, $signature) {
switch ($this->cryptParams['library']) {
case 'openssl':
return $this->verifyOpenSSL($data, $signature);
break;
}
}
public function getAlgorith() {
return $this->cryptParams['method'];
}
static function makeAsnSegment($type, $string) {
switch ($type){
case 0x02:
if (ord($string) > 0x7f)
$string = chr(0).$string;
break;
case 0x03:
$string = chr(0).$string;
break;
}
$length = strlen($string);
if ($length < 128){
$output = sprintf("%c%c%s", $type, $length, $string);
} else if ($length < 0x0100){
$output = sprintf("%c%c%c%s", $type, 0x81, $length, $string);
} else if ($length < 0x010000) {
$output = sprintf("%c%c%c%c%s", $type, 0x82, $length/0x0100, $length%0x0100, $string);
} else {
$output = NULL;
}
return($output);
}
/* Modulus and Exponent must already be base64 decoded */
static function convertRSA($modulus, $exponent) {
/* make an ASN publicKeyInfo */
$exponentEncoding = XMLSecurityKey::makeAsnSegment(0x02, $exponent);
$modulusEncoding = XMLSecurityKey::makeAsnSegment(0x02, $modulus);
$sequenceEncoding = XMLSecurityKey:: makeAsnSegment(0x30, $modulusEncoding.$exponentEncoding);
$bitstringEncoding = XMLSecurityKey::makeAsnSegment(0x03, $sequenceEncoding);
$rsaAlgorithmIdentifier = pack("H*", "300D06092A864886F70D0101010500");
$publicKeyInfo = XMLSecurityKey::makeAsnSegment (0x30, $rsaAlgorithmIdentifier.$bitstringEncoding);
/* encode the publicKeyInfo in base64 and add PEM brackets */
$publicKeyInfoBase64 = base64_encode($publicKeyInfo);
$encoding = "-----BEGIN PUBLIC KEY-----\n";
$offset = 0;
while ($segment=substr($publicKeyInfoBase64, $offset, 64)){
$encoding = $encoding.$segment."\n";
$offset += 64;
}
return $encoding."-----END PUBLIC KEY-----\n";
}
public function serializeKey($parent) {
}
/**
* Retrieve the X509 certificate this key represents.
*
* Will return the X509 certificate in PEM-format if this key represents
* an X509 certificate.
*
* @return The X509 certificate or NULL if this key doesn't represent an X509-certificate.
*/
public function getX509Certificate() {
return $this->x509Certificate;
}
/* Get the thumbprint of this X509 certificate.
*
* Returns:
* The thumbprint as a lowercase 40-character hexadecimal number, or NULL
* if this isn't a X509 certificate.
*/
public function getX509Thumbprint() {
return $this->X509Thumbprint;
}
/**
* Create key from an EncryptedKey-element.
*
* @param DOMElement $element The EncryptedKey-element.
* @return XMLSecurityKey The new key.
*/
public static function fromEncryptedKeyElement(DOMElement $element) {
$objenc = new XMLSecEnc();
$objenc->setNode($element);
if (! $objKey = $objenc->locateKey()) {
throw new Exception("Unable to locate algorithm for this Encrypted Key");
}
$objKey->isEncrypted = TRUE;
$objKey->encryptedCtx = $objenc;
XMLSecEnc::staticLocateKeyInfo($objKey, $element);
return $objKey;
}
}