Odyssey
cutrusted.i
1 <?php
2 
3 
4 require_once dirname(__FILE__). '/hcuCommon.i';
5 
6 // openssl supported ciphers:
7 // https://www.openssl.org/docs/man1.0.2/man1/openssl-enc.html
8 // Recommendation: When php version is upgraded to 7.1+, we
9 // may want to upgrade this to "aes-256-gcm", which may also
10 // require changes in the encryption functions in hcuCommon.i.
11 
12 // Constants for parm related encryption
13 define("PARMENCDEC_CIPHER_MODE", "aes-256-cbc");
14 // allowed values: sha1, sha256
15 define("PARMENCDEC_AUTH_HASH_ALGO", "sha256");
16 
17 // Constants for credentials encryption
18 define("CREDENTIALS_ENCDEC_CIPHER_MODE", "aes-128-cbc");
19 define("CREDENTIALS_AUTH_HASH_ALGO", "sha256");
20 
21 /**
22  * check if mcrypt library exists
23  */
24 function check_if_mcrypt_exists() {
25  if (!function_exists("mdecrypt_generic") && !function_exists("mcrypt_generic"))
26  throw new exception("MCRYPT library does not exist.");
27 }
28 
29 /**
30  * write cutrusteddetail given values in $parms
31  * tries update first, then insert
32  *
33  * @param dbhandle $dbh
34  * @param array $parms (string Cu, string trustedid, array fields)
35  * @return array
36  */
37 function cutd_write($dbh, $parms) {
38 
39  if (!isset($parms['Cu']) || !isset($parms['trustedid']) ||
40  !isset($parms['fields'])) {
41  $response['Response'] = 'false';
42  $response['Message'] = 'Missing Parameters';
43  } else {
44 
45 
46  $Cu = trim($parms['Cu']);
47  $MasterKey = sha1("${Cu}:3pk4osso");
48  $trustedid = trim($parms['trustedid']);
49  $fields=$parms['fields'];
50  $storeparms = json_encode($fields);
51 
52  $storeparms = parmencrypt($storeparms, $MasterKey);
53  $inssql = "insert into cutrusteddetail (cu, trustedid, parms) values ('$Cu','$trustedid','$storeparms')";
54  $updsql = "update cutrusteddetail set parms='$storeparms'
55  where cu='$Cu' and trustedid='$trustedid'";
56 
57  # try update - if rows_affected=1 $response='updated'
58  $sth = db_query($updsql, $dbh);
59  if (db_affected_rows($sth) == 1) {
60  $response['Response'] = 'true';
61  $response['Message'] = 'Updated';
62  } else {
63  # else try insert -
64 
65  $sth = db_query($inssql, $dbh);
66  if (db_affected_rows($sth) == 1) {
67  $response['Response'] = 'true';
68  $response['Message'] = 'Inserted';
69  } else {
70  $response['Response'] = 'false';
71  $response['Message'] = 'Failed';
72  }
73  }
74  }
75  $result['status'] = $response;
76  if ($response['Response'] == 'false') {
77  $result['data'] = array();
78  } else {
79  $result['data']["$Cu|$trustedid"] = $fields;
80  }
81  $result['status']['Errors'] = array();
82  return $result;
83 }
84 
85 /**
86  *
87  * read cutrusteddetail given Cu and trustedid in $parms
88  *
89  * @param dbhandle $dbh
90  * @param array $parms {string Cu, string trustedid}
91  * @return array
92  */
93 function cutd_read($dbh, $parms) {
94  if (!isset($parms['Cu']) || !isset($parms['trustedid'])) {
95  $response['Response'] = 'false';
96  $response['Message'] = 'Missing Parameters';
97  } else {
98 
99  $Cu = trim($parms['Cu']);
100  $MasterKey = sha1("${Cu}:3pk4osso");
101  $trustedid = trim($parms['trustedid']);
102 
103  $sql = "select parms from cutrusteddetail
104  where cu='$Cu' and trustedid='$trustedid'";
105  $sth = db_query($sql, $dbh);
106 
107  if (db_num_rows($sth) != 1) {
108  $response['Response'] = 'false';
109  $response['Message'] = 'Failed';
110  $response['sql']=$sql;
111  } else {
112 
113  $drow = db_fetch_array($sth, 0);
114 
115  $storefields = $drow['parms'];
116  $fields = parmdecrypt($storefields, $MasterKey);
117 
118  $fields = json_decode($fields, TRUE);
119 
120  if ($fields === NULL) {
121  $response['Response'] = 'false';
122  $response['Message'] = 'Failed';
123  } else {
124  $response['Response'] = 'true';
125  $response['Message'] = 'OK';
126  }
127  }
128  }
129  $result['status'] = $response;
130  if ($response['Response'] == 'false') {
131  $result['data'] = array();
132  } else {
133  $result['data']["$Cu|$trustedid"] = $fields;
134  }
135  $result['status']['Errors'] = array();
136  return $result;
137 }
138 
139 /*
140  *
141  * read cutrusteddetail given Cu and trustedid in $parms
142  * if no hit, read cutrustedmaster w/ given trustedid
143  *
144  * @param dbhandle $dbh
145  * @param array $parms {string Cu, string trustedid}
146  * @return array
147  */
148 function cutrusted_read($dbh, $parms) {
149  $result['status']['Response'] = 'true';
150  $result['status']['Message'] = 'OK';
151  $result['status']['Code'] = '000';
152  $result['status']['Errors'] = array();
153 
154  try {
155 
156  if (!isset($parms['Cu']) || !isset($parms['trustedid'])) {
157  throw new Exception('Missing Parameters', 100);
158  }
159  $Cu = trim($parms['Cu']);
160  $MasterKey = sha1("${Cu}:3pk4osso");
161  $trustedid = trim($parms['trustedid']);
162 
163  $sql = "select parms from cutrusteddetail
164  where cu='$Cu' and trustedid='$trustedid'";
165  $sth = db_query($sql, $dbh);
166 
167  if (db_num_rows($sth) == 1) {
168  $result['status']['Source']='detail';
169  $drow = db_fetch_array($sth, 0);
170 
171  $storefields = $drow['parms'];
172  $fields = parmdecrypt($storefields, $MasterKey);
173 
174  $fields = json_decode($fields, TRUE);
175 
176  if ($fields === NULL) {
177  throw new Exception("Field Decryption Failed", 100);
178  }
179  $result['data'] = $fields;
180  } else {
181  # no cu-specific record, try to read the master
182  $result = cutm_readdflt($dbh, $parms);
183  if ($result['status']['Response'] == 'false') {
184  $result['status']['Source']='';
185  } else {
186  $result['status']['Source']='master';
187  }
188 
189  }
190  } catch (Exception $e) {
191  $result['status']['Response'] = 'false';
192  $result['status']['Code'] = $e->getCode();
193  $result['status']['Message'] = "Failed";
194  $result['status']['Errors'] = array("(" . $e->getLine() . ") " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8', FALSE));
195  $result['status']['Source'] = '';
196  $result['data'] = array();
197  }
198  return $result;
199 }
200 
201 /**
202  *
203  * list cutrusteddetail records. Option values for Cu and trustedid may be given in $parms
204  * Valid params: trustedid -- one trustedid, trustedids -- expects an array, uses the IN syntax of the select statement
205  *
206  * @param dbhandle $dbh
207  * @param array $parms (string Cu, string trustedid)
208  * @return type
209  */
210 function cutd_list($dbh, $parms) {
211 
212  $Cu = trim($parms['Cu']);
213  $trustedid = (isset($parms['trustedid']) ? trim($parms['trustedid']) : '');
214  $delim = 'where';
215  $culimit = '';
216  $trustlimit = '';
217 
218  if (!empty($Cu)) {
219  $culimit = "$delim cu='$Cu'";
220  $delim = 'and';
221  }
222  if (!empty($trustedid)) {
223  $trustlimit = "$delim trustedid = '$trustedid'";
224  }
225  else if (isset($parms["trustedids"]) && is_array($parms["trustedids"]) && count($parms["trustedids"]) > 0)
226  $trustlimit = "$delim trustedid in ('" . implode("','", $parms["trustedids"]) . "')";
227 
228  $sql = "select cu, trustedid, parms from cutrusteddetail $culimit $trustlimit order by trustedid, cu";
229  $sth = db_query($sql, $dbh);
230 
231  $numrows = db_num_rows($sth);
232  if ($numrows == 0) {
233  $result['status']['Response'] = 'false';
234  $result['status']['Message'] = 'Failed';
235  $result['status']['Errors'] = array("No Records Found");
236  } else {
237  $result['status']['Response'] = 'true';
238  $result['status']['Message'] = 'OK';
239  $result['status']['Errors'] = array();
240 
241  for ($i = 0; $i < $numrows; $i++) {
242  $drow = db_fetch_array($sth, $i);
243 
244  $Cu = trim($drow['cu']);
245  $MasterKey = sha1("${Cu}:3pk4osso");
246  $trustedid = trim($drow['trustedid']);
247  $storefields = trim($drow['parms']);
248  $fields = parmdecrypt($storefields, $MasterKey);
249  $fields = json_decode($fields, TRUE);
250  $result['data']["$Cu|$trustedid"]['cu'] = $Cu;
251  $result['data']["$Cu|$trustedid"]['trustedid'] = $trustedid;
252  $result['data']["$Cu|$trustedid"]['fields'] = $fields;
253  }
254  }
255 
256  return $result;
257 }
258 /**
259  *
260  * write cutrustedmaster given values in $parms
261  * tries update first, then insert
262  *
263  * @param dbhandle $dbh
264  * @param array $parms (string trustedid, string trustedvendor, string trustedtype, string hcuinterface)
265  * @return array
266  */
267 function cutm_write($dbh, $parms) {
268 
269  if (!isset($parms['trustedid']) ||
270  !isset($parms['fields']) ||
271  !isset($parms['trustedvendor']) ||
272  !isset($parms['trustedtype']) ||
273  !isset($parms['hcuinterface'])) {
274  $response['Response'] = 'false';
275  $response['Message'] = 'Missing Parameters';
276  } else {
277  $trustedid = trim($parms['trustedid']);
278  $trustedvendor = trim($parms['trustedvendor']);
279  $trustedtype = trim($parms['trustedtype']);
280  $hcuinterface = trim($parms['hcuinterface']);
281  $fields = $parms['fields'];
282  $storefields = json_encode($fields);
283 
284  $inssql = "insert into cutrustedmaster (trustedid, trustedvendor,trustedtype,hcuinterface,trustedfields)
285  values ('$trustedid','$trustedvendor','$trustedtype','$hcuinterface','$storefields')";
286  $updsql = "update cutrustedmaster set trustedvendor='$trustedvendor',
287  trustedtype='$trustedtype', hcuinterface='$hcuinterface',
288  trustedfields='$storefields'
289  where trustedid='$trustedid'";
290 
291  # try update - if rows_affected=1 $response='updated'
292  $sth = db_query($updsql, $dbh);
293  if (db_affected_rows($sth) == 1) {
294  $response['Response'] = 'true';
295  $response['Message'] = 'Updated';
296  } else {
297  # else try insert -
298 
299  $sth = db_query($inssql, $dbh);
300  if (db_affected_rows($sth) == 1) {
301  $response['Response'] = 'true';
302  $response['Message'] = 'Inserted';
303  } else {
304  $response['Response'] = 'false';
305  $response['Message'] = 'Failed';
306  }
307  }
308  }
309  $result['status'] = $response;
310  if ($response['Response'] == 'false') {
311  $result['data'] = array();
312  } else {
313  $result['data']["$trustedid"] = $fields;
314  }
315  $result['status']['Errors'] = array();
316  return $result;
317 }
318 /**
319  * read cutrustedmaster given trustedid in $parms
320  *
321  * @param dbhandle $dbh
322  * @param array $parms (string trustedid)
323  * @return array
324  */
325 function cutm_read($dbh, $parms) {
326 
327  if (!isset($parms['trustedid'])) {
328  $response['Response'] = 'false';
329  $response['Message'] = 'Missing Parameters';
330  } else {
331  $trustedid = trim($parms['trustedid']);
332 
333  $sql = "select trustedvendor, trustedtype, hcuinterface, trustedfields from cutrustedmaster
334  where trustedid='$trustedid'";
335  $sth = db_query($sql, $dbh);
336 
337  if (db_num_rows($sth) != 1) {
338  $response['Response'] = 'false';
339  $response['Message'] = 'Failed';
340  } else {
341  $drow = db_fetch_array($sth, 0);
342  $trustedvendor = trim($drow['trustedvendor']);
343  $trustedtype = trim($drow['trustedtype']);
344  $hcuinterface = trim($drow['hcuinterface']);
345  $storedfields = trim($drow['trustedfields']);
346  $trustedfields = json_decode($storedfields, TRUE);
347 
348  if ($trustedfields === NULL) {
349  $response['Response'] = 'false';
350  $response['Message'] = 'Failed';
351  $response[storedfields] = $storedfields;
352  } else {
353  $response['Response'] = 'true';
354  $response['Message'] = 'OK';
355  }
356  }
357  }
358  $result['status'] = $response;
359  if ($response['Response'] == 'false') {
360  $result['data'] = array();
361  } else {
362  $result['data']['trustedid'] = $trustedid;
363  $result['data']['trustedvendor'] = $trustedvendor;
364  $result['data']['trustedtype'] = $trustedtype;
365  $result['data']['hcuinterface'] = $hcuinterface;
366  $result['data']['trustedfields'] = $trustedfields;
367  }
368  $result['status']['Errors'] = array();
369  return $result;
370 }
371 /**
372  * read cutrustedmaster given trustedid in $parms
373  * return default values
374  * @param dbhandle $dbh
375  * @param array $parms (string trustedid)
376  * @return array
377  */
378 function cutm_readdflt($dbh, $parms) {
379 
380  if (!isset($parms['trustedid'])) {
381  $response['Response'] = 'false';
382  $response['Message'] = 'Missing Parameters';
383  } else {
384  $trustedid = trim($parms['trustedid']);
385 
386  $sql = "select trustedvendor, trustedtype, hcuinterface, trustedfields from cutrustedmaster
387  where trustedid='$trustedid'";
388  $sth = db_query($sql, $dbh);
389 
390  if (db_num_rows($sth) != 1) {
391  $response['Response'] = 'false';
392  $response['Message'] = 'Failed';
393  } else {
394  $drow = db_fetch_array($sth, 0);
395  $trustedvendor = trim($drow['trustedvendor']);
396  $trustedtype = trim($drow['trustedtype']);
397  $hcuinterface = trim($drow['hcuinterface']);
398  $storedfields = trim($drow['trustedfields']);
399  $trustedfields = json_decode($storedfields, TRUE);
400 
401  if ($trustedfields === NULL) {
402  $response['Response'] = 'false';
403  $response['Message'] = 'Failed';
404  $response['storedfields'] = $storedfields;
405  } else {
406  $response['Response'] = 'true';
407  $response['Message'] = 'OK';
408  }
409  }
410  }
411  $result['status'] = $response;
412  if ($response['Response'] == 'false') {
413  $result['data'] = array();
414  } else {
415  $result['master']['trustedid'] = $trustedid;
416  $result['master']['trustedvendor'] = $trustedvendor;
417  $result['master']['trustedtype'] = $trustedtype;
418  $result['master']['hcuinterface'] = $hcuinterface;
419  $result['master']['trustedfields'] = $trustedfields;
420  foreach ($trustedfields as $fldkey => $fldval) {
421  if (isset($fldval['Default'])) {
422  $result['data'][$fldkey] = $fldval['Default'];
423  }
424  }
425  }
426  $result['status']['Errors'] = array();
427  return $result;
428 }
429 /**
430  *
431  * list cutrustedmaster records. Value for trustedid may be given in $parms
432  *
433  * @param dbhandle $dbh
434  * @param array $parms (string trustedid)
435  * @return type
436  */
437 function cutm_list($dbh, $parms) {
438 
439  $trustlimit = "";
440  $delim = "where";
441  if (HCU_array_key_exists("trustedid", $parms)) {
442  $trustedid = trim($parms['trustedid']);
443  $trustlimit = "$delim trustedid = '$trustedid'";
444  $delim = "and";
445  }
446 
447  $sql = "select trustedid, trustedvendor, trustedtype, hcuinterface, trustedfields from cutrustedmaster $trustlimit order by trustedid";
448  $sth = db_query($sql, $dbh);
449 
450  $numrows = db_num_rows($sth);
451  if ($numrows == 0) {
452  $result['status']['Response'] = 'false';
453  $result['status']['Message'] = 'Failed';
454  $result['status']['Errors'] = array("No Records Found");
455  } else {
456  $result['status']['Response'] = 'true';
457  $result['status']['Message'] = 'OK';
458  $result['status']['Errors'] = array();
459 
460  for ($i = 0; $i < $numrows; $i++) {
461  $drow = db_fetch_array($sth, $i);
462 
463  $trustedid = trim($drow['trustedid']);
464  $trustedvendor = trim($drow['trustedvendor']);
465  $trustedtype = trim($drow['trustedtype']);
466  $hcuinterface = trim($drow['hcuinterface']);
467  $storefields = trim($drow['trustedfields']);
468  $fields = json_decode($storefields, TRUE);
469  $result['data']["$trustedid"]['trustedid'] = $trustedid;
470  $result['data']["$trustedid"]['trustedvendor'] = $trustedvendor;
471  $result['data']["$trustedid"]['trustedtype'] = $trustedtype;
472  $result['data']["$trustedid"]['hcuinterface'] = $hcuinterface;
473  $result['data']["$trustedid"]['fields'] = $fields;
474  }
475  }
476 
477  return $result;
478 }
479 /**
480  *
481  * list cutrustedmaster and related cutrusteddetail records. Optional value for trustedid may be given in $parms
482  *
483  * @param dbhandle $dbh
484  * @param array $parms (trustedid)
485  * @return array
486  */
487 function cutrusted_list($dbh, $parms) {
488 
489  $trustedid = trim($parms['trustedid']);
490  $delim = 'where';
491 
492  if (!empty($trustedid)) {
493  $trustlimit = "$delim trustedid = '$trustedid'";
494  $delim = 'and';
495  }
496 
497  $sql = "select trustedid, trustedvendor, trustedtype, hcuinterface, trustedfields from cutrustedmaster $trustlimit order by trustedid";
498  $sth = db_query($sql, $dbh);
499 
500  $numrows = db_num_rows($sth);
501  if ($numrows == 0) {
502  $result['status']['Response'] = 'false';
503  $result['status']['Message'] = 'Failed';
504  $result['status']['Errors'] = array("No Records Found");
505  } else {
506  $result['status']['Response'] = 'true';
507  $result['status']['Message'] = 'OK';
508  $result['status']['Errors'] = array();
509 
510  for ($i = 0; $i < $numrows; $i++) {
511  $drow = db_fetch_array($sth, $i);
512 
513  $trustedid = trim($drow['trustedid']);
514  $trustedvendor = trim($drow['trustedvendor']);
515  $trustedtype = trim($drow['trustedtype']);
516  $hcuinterface = trim($drow['hcuinterface']);
517  $storefields = trim($drow['trustedfields']);
518  $fields = json_decode($storefields, TRUE);
519  $result['data']["$trustedid"]['trustedid'] = $trustedid;
520  $result['data']["$trustedid"]['trustedvendor'] = $trustedvendor;
521  $result['data']["$trustedid"]['trustedtype'] = $trustedtype;
522  $result['data']["$trustedid"]['hcuinterface'] = $hcuinterface;
523  $result['data']["$trustedid"]['fields'] = $fields;
524  $cutdlist = cutd_list($dbh, array('trustedid' => $trustedid));
525  if ($cutdlist['status']['Response'] == 'true') {
526  $result['data']["$trustedid"]['clients'] = $cutdlist['data'];
527  } else {
528  $result['data']["$trustedid"]['clients'] = array();
529  }
530  }
531  }
532 
533  return $result;
534 }
535 
536 /**
537  * Openssl based parmencrypt encryption function.
538  */
539 function parmencrypt($str,
540  $key,
541  $cipher_method=PARMENCDEC_CIPHER_MODE) {
542  try {
543  if (!is_null($str) && trim($str) != ''){
544  $enc_resp = hcuOpenSSLEncrypt($str,
545  $key,
546  $method=$cipher_method,
547  $auth_hash_algo=PARMENCDEC_AUTH_HASH_ALGO);
548 
549  $ciphertext = $enc_resp["message"];
550  $hash_hmac = $enc_resp["hash"];
551  return base64_encode($hash_hmac.$ciphertext);
552  } else {
553  return $str;
554  }
555  } catch (Exception $ex) {
556  throw $ex;
557  }
558 
559 }
560 
561 /**
562  * To be deleted once migrated to openssl based encryption.
563  * Is not being called from anywhere, except some test cases
564  * that do not make calls if this function is deleted (safe).
565  */
566 function parmencrypt_mcrypt($str, $key) {
567  check_if_mcrypt_exists();
568  $key_size = mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
569  $key = substr($key, 0, $key_size);
570  $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
571  $blocksize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
572  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
573  $str = addpadding($str, $blocksize);
574  return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_ECB, $iv));
575 }
576 
577 /**
578  * This function is later to be renamed as parmdecrypt. and
579  * the old parmdecrypt function will be deprecated.
580  *
581  * returns:
582  * decrypted text or False
583  */
584 function parmdecrypt_openssl($str,
585  $key,
586  $cipher_method) {
587  try {
588  $cipher_all = base64_decode($str);
589 
590  if(PARMENCDEC_AUTH_HASH_ALGO == "sha256") {
591  $auth_hash_len = 32; // bytes
592  }
593  // PARMENCDEC_AUTH_HASH_ALGO == "sha1"
594  else {
595  $auth_hash_len = 16; //bytes
596  }
597 
598  $encrypted_hash = substr($cipher_all, 0, $auth_hash_len);
599  $ciphertext = substr($cipher_all, $auth_hash_len);
600 
601  return hcuOpenSSLDecrypt($ciphertext,
602  $encrypted_hash,
603  $key,
604  $method=$cipher_method,
605  $auth_hash_algo=PARMENCDEC_AUTH_HASH_ALGO);
606  } catch (Exception $ex) {
607  return False;
608  }
609 }
610 
611 
612 /**
613  * Decryption support for MCRYPT is temporary and deprecated.
614  * Use of this function is not advised and need to be deleted in
615  * the near future by replacing with openssl based encryption api.
616  *
617  * returns:
618  * decrypted text or false
619  */
620 function parmdecrypt_mcrypt($orig_str, $orig_key) {
621  try{
622  check_if_mcrypt_exists();
623  $base64_str = base64_decode($orig_str);
624  $key_size = mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
625  $key = substr($orig_key, 0, $key_size);
626  $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
627  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
628  $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $base64_str, MCRYPT_MODE_ECB, $iv);
629  return strippadding($str);
630  } catch (exception $ex) {
631  return false;
632  }
633 
634 }
635 
636 /**
637  * Returns decrypted data or raises exception
638  *
639  * first try with openssl
640  * if failed, try with mcrypt
641  * if failed, raise exception
642  *
643  * 2019/03/15: TO BE UPDATED LATER TO ONLY USE OPENSSL
644  * AND DELETE BOTH parmdecrypt_mcrypt and
645  * parmdecrypt_openssl functions.
646  */
647 function parmdecrypt($orig_str,
648  $orig_key,
649  $cipher_method=PARMENCDEC_CIPHER_MODE) {
650  try {
651  if(!is_null($orig_str) && trim($orig_str) != '') {
652  $openssl_decrypt_result = parmdecrypt_openssl($orig_str,
653  $orig_key,
654  $cipher_method=$cipher_method);
655  // NOTE: code block in if section will be deleted along with
656  // parmdecrypt_mcrypt function and parmdecrypt_openssl will be
657  // merged here
658 
659  // unable to decrypt with openssl_decrypt
660  if($openssl_decrypt_result == False) {
661  $mcrypt_decrypt_result = parmdecrypt_mcrypt($orig_str, $orig_key);
662  if ($mcrypt_decrypt_result == false) {
663  // Error, could not be decrypted with either api: mcrypt or openssl
664  throw new exception("Error: Parm could not be decrypted.");
665  }
666  else {
667  // successfully decrypted using mcrypt
668  return $mcrypt_decrypt_result;
669  }
670  } else {
671  // successfully decrypted using openssl
672  return $openssl_decrypt_result;
673  }
674  } else {
675  return $orig_str;
676  }
677  } catch(Exception $ex){
678  throw $ex;
679  }
680 }
681 
682 /**
683  * TO BE DELETED AFTER COMPLETE OPENSSL MIGRATION.
684  */
685 function EncryptCredentialsMcrypt($str,
686  $key,
687  $iv="") {
688  try {
689  check_if_mcrypt_exists();
690  $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
691  $blocksize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
692  $str = addpadding($str, $blocksize);
693 
694  $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
695  if ($iv =="") $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
696  mcrypt_generic_init($td, $key, $iv);
697  $token = mcrypt_generic($td, $str);
698  mcrypt_generic_deinit($td);
699  mcrypt_module_close($td);
700 
701  return array(base64_encode($token), base64_encode($iv));
702 
703  } catch (exception $ex) {
704  return false;
705  }
706 }
707 
708 /**
709  *
710  * $str : only ciphertext, no IV attached
711  * $key : secret key
712  * $iv : Initialization vector used for encryption (if passed,
713  * length must match openssl requirement. see: openssl_cipher_iv_length and
714  * openssl_random_pseudo_bytes($ivsize))
715  * $cipher_method : current cipher method being used for openssl
716  *
717  * Note: no authenticity check is being done!
718  *
719  */
720 function EncryptCredentials($str,
721  $key,
722  $iv="",
723  $cipher_method=CREDENTIALS_ENCDEC_CIPHER_MODE) {
724  try {
725  $encResp = hcuOpenSSLEncrypt($str,
726  $key,
727  $method=$cipher_method,
728  $auth_hash_algo=CREDENTIALS_AUTH_HASH_ALGO,
729  $auth_hash_binary=true,
730  $iv=$iv,
731  $context="credentials");
732 
733  $ciphertext = $encResp["message"];
734  $iv_enc = $encResp["iv"];
735 
736  return array(base64_encode($ciphertext), base64_encode($iv_enc));
737 
738  } catch (Exception $ex) {
739  throw $ex;
740  }
741 }
742 
743 /**
744  * FOR BACKWARDS COMPATIBILITY WITH MCRYPT: TO BE DEPRECATED
745  *
746  * Previous implementation did not require
747  * Recipient needs to know the IV used for encryption
748  * it in order to decrypt the data (or verify the hash, etc.)."
749  *
750  * $str: ciphertext (not involving IV)
751  * $key: secret key
752  * $iv : IV used for encrypting the initial message.
753  *
754  * returns:
755  * decrypted data with mcrypt or false on failure.
756  */
757 function DecryptCredentialsMcrypt($str, $key, $iv) {
758  try {
759  check_if_mcrypt_exists();
760  $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128,
761  $key,
762  base64_decode($str),
763  MCRYPT_MODE_CBC,
764  base64_decode($iv));
765  return strippadding($str);
766  } catch (exception $ex) {
767  return false;
768  }
769 }
770 
771 /**
772  * TO BE MERGED IN DecryptCredentials
773  *
774  * $str : only ciphertext, no IV attached
775  * $key : secret key
776  * $iv : Initialization vector used for encryption
777  * $cipher_method : current cipher method being used for openssl
778  */
779 function DecryptCredentialsOpenssl($str,
780  $key,
781  $iv,
782  $cipher_method) {
783  try {
784  $ciphertext = base64_decode($str);
785  if($iv != "") {
786  $iv = base64_decode($iv);
787  }
788  $encrypted_hash = "";
789  return hcuOpenSSLDecrypt($ciphertext,
790  $encrypted_hash,
791  $key,
792  $method=$cipher_method,
793  $auth_hash_algo=CREDENTIALS_AUTH_HASH_ALGO,
794  $auth_hash_binary=true,
795  $iv=$iv,
796  $context="credentials");
797 
798  } catch (exception $ex) {
799  return False;
800  }
801 }
802 
803 /**
804  * Returns decrypted data or raises exception
805  *
806  * first try with openssl
807  * if failed, try with mcrypt
808  * if failed, raise exception
809  *
810  * 2019/03/15: TO BE UPDATED LATER TO ONLY USE OPENSSL
811  * AND DELETE both DecryptCredentialsMcrypt
812  * DecryptCredentialsOpenssl functions.
813  */
814 function DecryptCredentials($str,
815  $key,
816  $iv,
817  $cipher_method=CREDENTIALS_ENCDEC_CIPHER_MODE) {
818  try {
819  $openssl_result = DecryptCredentialsOpenssl($str,
820  $key,
821  $iv,
822  $cipher_method);
823  if ($openssl_result == False) {
824  $mcrypt_result = DecryptCredentialsMcrypt($str, $key, $iv);
825 
826  if($mcrypt_result == false) {
827  throw new exception("Credential could not be decrypted.");
828  } else {
829  return $mcrypt_result;
830  }
831  } else {
832  return $openssl_result;
833  }
834 
835  } catch (exception $ex) {
836  throw $ex;
837  }
838 }
839 
840 function addpadding($string, $blocksize = 32) {
841  # implements PKCS7 padding
842  $len = strlen($string);
843  $pad = $blocksize - ($len % $blocksize);
844  $string .= str_repeat(chr($pad), $pad);
845  return $string;
846 }
847 
848 function strippadding($string) {
849  $slast = ord(substr($string, -1));
850  $slastc = chr($slast);
851 
852  $match= "/\\x" . dechex($slast) . "{" . $slast . "}/";
853 
854  if (strlen($string) && preg_match($match, $string)) {
855  $string = substr($string, 0, strlen($string) - $slast);
856  return $string;
857  } else {
858  return false;
859  }
860 }
861 
862 ?>