Subversion Repositories php_utils

Rev

Rev 49 | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * ISO/IEC 7816 Application Identifier decoder for PHP
  5.  * Copyright 2022 Daniel Marschall, ViaThinkSoft
  6.  * Version 2022-09-20
  7.  *
  8.  * Licensed under the Apache License, Version 2.0 (the "License");
  9.  * you may not use this file except in compliance with the License.
  10.  * You may obtain a copy of the License at
  11.  *
  12.  *     http://www.apache.org/licenses/LICENSE-2.0
  13.  *
  14.  * Unless required by applicable law or agreed to in writing, software
  15.  * distributed under the License is distributed on an "AS IS" BASIS,
  16.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17.  * See the License for the specific language governing permissions and
  18.  * limitations under the License.
  19.  */
  20.  
  21. // Definition of Application Identifiers (AID):
  22. // - ISO 7816-05:1994 (1st ed.), clause 5.2
  23. // - ISO 7816-04:2005 (2nd ed.), clause 8.2.1.2, Annex A.1, Annex D
  24. // - ISO 7816-04:2013 (3rd ed.), clause 12.2.3, Annex A.1, Annex D
  25. // - ISO 7816-04:2020 (4th ed.), clause 12.3.4, Annex A.1, Annex D
  26.  
  27. include_once __DIR__ . '/gmp_supplement.inc.php';
  28. include_once __DIR__ . '/misc_functions.inc.php';
  29.  
  30. # ---
  31.  
  32. /*
  33. #test2('A000000051AABBCC'); // International Registration
  34. #test2('B01234567890'); // Illegal AID (RFU)
  35. #test2('D276000098AABBCCDDEEFFAABBCCDDEE'); // National Registration
  36. #test2('F01234567890'); // Unregistered AID
  37. #test('91234FFF999'); // IIN based AID
  38. #test('51234FFF999'); // IIN based AID
  39. test('E828BD080F014E585031'); // ISO E8-OID 1.0.aaaa
  40. test('E80704007F00070304'); // BSI Illegal E8-OID-AID (with DER Length)
  41. test('E80704007F0007030499'); // BSI Illegal E8-OID-AID + PIX (PIX is never used by BSI; it's just for us to test)
  42. test('E829112233'); // Possible other illegal E8-OID
  43.  
  44. function test2($aid) {
  45.         while ($aid != '') {
  46.                 echo test($aid);
  47.                 $aid = substr($aid,0,strlen($aid)-1);
  48.         }
  49. }
  50.  
  51. function test($aid) {
  52.         $out = _decode_aid($aid);
  53.         $max_key_len = 32; // min width of first column
  54.         foreach ($out as $a) {
  55.                 if (is_array($a)) {
  56.                         $max_key_len = max($max_key_len,strlen($a[0]));
  57.                 }
  58.         }
  59.         foreach ($out as $a) {
  60.                 if (is_array($a)) {
  61.                         echo str_pad($a[0],$max_key_len,' ',STR_PAD_RIGHT).'  '.$a[1]."\n";
  62.                 } else {
  63.                         echo $a."\n";
  64.                 }
  65.         }
  66.         echo "\n";
  67. }
  68. */
  69.  
  70. # ---
  71.  
  72. function _aid_e8_oid_helper($output_oid,$by,$ii,&$ret,$minmax_measure,$min,$max) {
  73.         if ($minmax_measure == 'ARC') {
  74.                 if (($min!=-1) && (count($output_oid)<$min)) return true;  // continue
  75.                 if (($max!=-1) && (count($output_oid)>$max)) return false; // stop
  76.         } else if ($minmax_measure == 'DER') {
  77.                 if (($min!=-1) && ($ii+1<$min)) return true;  // continue
  78.                 if (($max!=-1) && ($ii+1>$max)) return false; // stop
  79.         }
  80.  
  81.         $byy = $by;
  82.         for ($i=0;$i<=$ii;$i++) array_shift($byy);
  83.  
  84.         $is_iso_standard = (count($output_oid) >= 3) && ($output_oid[0] == '1') && ($output_oid[1] == '0');
  85.  
  86.         $s_oid = implode('.',$output_oid);
  87.  
  88.         if ($is_iso_standard) {
  89.                 $std_hf = 'Standard ISO/IEC '.$output_oid[2];
  90.                 if (isset($output_oid[3])) $std_hf .= "-".$output_oid[3];
  91.         } else {
  92.                 $std_hf = "Unknown Standard"; // should not happen
  93.         }
  94.  
  95.         $pix = implode(':',$byy);
  96.  
  97.         if ($pix !== '') {
  98.                 $ret[] = array($ii+1,"$std_hf (OID $s_oid)",$pix);
  99.         } else {
  100.                 $ret[] = array($ii+1,"$std_hf (OID $s_oid)","");
  101.         }
  102.  
  103.         return true;
  104. }
  105.  
  106. function _aid_e8_interpretations($pure_der, $minmax_measure='ARC', $min=-1, $max=-1) {
  107.         $ret = array();
  108.  
  109.         $output_oid = array();
  110.  
  111.         $pure_der = strtoupper(str_replace(' ','',$pure_der));
  112.         $pure_der = strtoupper(str_replace(':','',$pure_der));
  113.         $by = str_split($pure_der,2);
  114.  
  115.         // The following part is partially taken from the DER decoder/encoder by Daniel Marschall:
  116.         // https://github.com/danielmarschall/oidconverter/blob/master/php/OidDerConverter.class.phps
  117.         // (Only the DER "value" part, without "type" and "length")
  118.  
  119.         $part = 2; // DER part 0 (type) and part 1 (length) not present
  120.         $fSub = 0; // Subtract value from next number output. Used when encoding {2 48} and up
  121.         $ll = gmp_init(0);
  122.         $arcBeginning = true;
  123.  
  124.         foreach ($by as $ii => $pb) {
  125.  
  126.                 $pb = hexdec($pb);
  127.  
  128.                 if ($part == 2) { // First two arcs
  129.                         $first = floor($pb / 40);
  130.                         $second = $pb % 40;
  131.                         if ($first > 2) {
  132.                                 $first = 2;
  133.                                 $output_oid[] = $first;
  134.                                 if (!_aid_e8_oid_helper($output_oid, $by, $ii, $ret, $minmax_measure, $min, $max)) break;
  135.                                 $arcBeginning = true;
  136.  
  137.                                 if (($pb & 0x80) != 0) {
  138.                                         // 2.48 and up => 2+ octets
  139.                                         // Output in "part 3"
  140.  
  141.                                         if ($pb == 0x80) {
  142.                                                 throw new Exception("Encoding error. Illegal 0x80 paddings. (See Rec. ITU-T X.690, clause 8.19.2)\n");
  143.                                         } else {
  144.                                                 $arcBeginning = false;
  145.                                         }
  146.  
  147.                                         $ll = gmp_add($ll, ($pb & 0x7F));
  148.                                         $fSub = 80;
  149.                                         $fOK = false;
  150.                                 } else {
  151.                                         // 2.0 till 2.47 => 1 octet
  152.                                         $second = $pb - 80;
  153.                                         $output_oid[] = $second;
  154.                                         if (!_aid_e8_oid_helper($output_oid, $by, $ii, $ret, $minmax_measure, $min, $max)) break;
  155.                                         $arcBeginning = true;
  156.                                         $fOK = true;
  157.                                         $ll = gmp_init(0);
  158.                                 }
  159.                         } else {
  160.                                 // 0.0 till 0.37 => 1 octet
  161.                                 // 1.0 till 1.37 => 1 octet
  162.                                 $output_oid[] = $first;
  163.                                 $output_oid[] = $second;
  164.                                 if (!_aid_e8_oid_helper($output_oid, $by, $ii, $ret, $minmax_measure, $min, $max)) break;
  165.                                 $arcBeginning = true;
  166.                                 $fOK = true;
  167.                                 $ll = gmp_init(0);
  168.                         }
  169.                         $part++;
  170.                 } else { //else if ($part == 3) { // Arc three and higher
  171.                         if (($pb & 0x80) != 0) {
  172.                                 if ($arcBeginning && ($pb == 0x80)) {
  173.                                         throw new Exception("Encoding error. Illegal 0x80 paddings. (See Rec. ITU-T X.690, clause 8.19.2)");
  174.                                 } else {
  175.                                         $arcBeginning = false;
  176.                                 }
  177.  
  178.                                 $ll = gmp_mul($ll, 0x80);
  179.                                 $ll = gmp_add($ll, ($pb & 0x7F));
  180.                                 $fOK = false;
  181.                         } else {
  182.                                 $fOK = true;
  183.                                 $ll = gmp_mul($ll, 0x80);
  184.                                 $ll = gmp_add($ll, $pb);
  185.                                 $ll = gmp_sub($ll, $fSub);
  186.                                 $output_oid[] = gmp_strval($ll, 10);
  187.  
  188.                                 if (!_aid_e8_oid_helper($output_oid, $by, $ii, $ret, $minmax_measure, $min, $max)) break;
  189.  
  190.                                 // Happens only if 0x80 paddings are allowed
  191.                                 // $fOK = gmp_cmp($ll, 0) >= 0;
  192.                                 $ll = gmp_init(0);
  193.                                 $fSub = 0;
  194.                                 $arcBeginning = true;
  195.                         }
  196.                 }
  197.         }
  198.  
  199.         return $ret;
  200. }
  201.  
  202. function _aid_e8_length_usage($aid) {
  203.         // Return true if $aid is most likely E8+Length+OID  (not intended by ISO)
  204.         // Return false if $aid is most likely E8+OID     (defined by ISO for their OID 1.0)
  205.         // Return null if it is ambiguous
  206.  
  207.         assert(substr($aid,0,2) === 'E8');
  208.         $len = substr($aid,2,2);
  209.         $rest = substr($aid,4);
  210.         $rest_num_bytes = floor(strlen($rest)/2);
  211.  
  212.         $is_e8_len_oid = false;
  213.         $is_e8_oid = false;
  214.  
  215.         // There are not enough following bytes, so it cannot be E8+Length+OID. It must be E8+OID
  216.         if ($len > $rest_num_bytes) $is_e8_oid = true;
  217.  
  218.         // E8 00 ... must be E8+OID, with OID 0.0.xx (recommendation), because Length=0 is not possible
  219.         if ($len == 0) $is_e8_oid = true;
  220.  
  221.         // E8 01 ... must be E8+Length+OID, because OID 0.1 (question) was never used
  222.         if ($len == 1) $is_e8_len_oid = true;
  223.  
  224.         // E8 02 refers to OID 0.2 (administration) but could also refer to a length
  225.         //if ($len == 2) return null;
  226.  
  227.         // E8 03 refers to OID 0.3 (network-operator) but could also refer to a length
  228.         //if ($len == 3) return null;
  229.  
  230.         // E8 04 refers to OID 0.4 (identified-organization) but could also refer to a length
  231.         //if ($len == 4) return null;
  232.  
  233.         // E8 05 refers to OID 0.5 (r-recommendation) but could also refer to a length
  234.         //if ($len == 5) return null;
  235.  
  236.         // E8 06-08 refers to OID 0.6-8, which are not defined, E8+Length+OID
  237.         if (($len >= 6) && ($len <= 8)) $is_e8_len_oid = true;
  238.  
  239.         // E8 09 refers to OID 0.9, which can be an OID or a Length
  240.         if ($len == 9) {
  241.                 // The only legal child of OID 0.9 is OID 0.9.2342 ($len=09, $rest=9226); then it is E8+OID
  242.                 // An OID beginning with DER encoding 9226 would be 2.2262, which is very unlikely
  243.                 if (substr($rest,0,4) === '9226') {
  244.                         // 09 92 26 is OID 0.9.2342, which is a valid OID (the only valid OID) => valid OID
  245.                         // 92 26 would be OID 2.2262 which is most likely not a valid OID      => invalid Len
  246.                         $is_e8_oid = true;
  247.                 } else {
  248.                         // Any other child inside 0.9 except for 2342 is illegal, so it must be length
  249.                         $is_e8_len_oid = true;
  250.                 }
  251.         }
  252.  
  253.         // E8 10-14 refers to OID 0.10-14 which is not defined. Therefore it must be E8+Length+OID
  254.         if (($len >= 10) && ($len <= 14)) $is_e8_len_oid = true;
  255.  
  256.         // If E8+Length+OID, then Len can max be 14, because E8 takes 1 byte, length takes 1 byte, and AID must be max 16 bytes
  257.         if ($len > 14) $is_e8_oid = true;
  258.  
  259.         // There is at least one case where the usage of E8+Length+OID is known:
  260.         //    Including the DER Encoding "Length" is not defined by ISO but used illegally
  261.         //    by German BSI (beside the fact that ISO never allowed anyone else to use E8-AIDs outside
  262.         //    of OID arc 1.0),
  263.         //    e.g. AID E80704007F00070302 defined by "BSI TR-03110" was intended to represent 0.4.0.127.0.7.3.2
  264.         //                                "more correct" would have been AID E804007F00070302
  265.         //         AID E80704007F00070304 defined by "BSI TR-03109-2" was intended to represent 0.4.0.127.0.7.3.4
  266.         //                                "more correct" would have been AID E804007F00070304
  267.         if (substr($rest,0,10) == '04007F0007'/*0.4.0.127.0.7*/) $is_e8_len_oid = $len <= 14;
  268.  
  269.         // Now conclude
  270.         if (!$is_e8_oid &&  $is_e8_len_oid) return true/*E8+Length+OID*/;
  271.         if ( $is_e8_oid && !$is_e8_len_oid) return false/*E8+OID*/;
  272.         return null/*ambiguous*/;
  273. }
  274.  
  275. function decode_aid($aid,$compact=true) {
  276.         $sout = '';
  277.         if (strtolower(substr($aid,0,2)) == '0x') $aid = substr($aid,2);
  278.         $out = _decode_aid($aid);
  279.         if ($compact) {
  280.                 $max_key_len = 0;
  281.                 foreach ($out as $a) {
  282.                         if (is_array($a)) {
  283.                                 $max_key_len = max($max_key_len,strlen($a[0]));
  284.                         }
  285.                 }
  286.         } else {
  287.                 $max_key_len = 32; // 16 bytes
  288.         }
  289.         foreach ($out as $a) {
  290.                 if (is_array($a)) {
  291.                         $sout .= str_pad($a[0],$max_key_len,' ',STR_PAD_RIGHT).'   '.$a[1]."\n";
  292.                 } else {
  293.                         $sout .= $a."\n";
  294.                 }
  295.         }
  296.         return $sout;
  297. }
  298.  
  299. function _is_bcd($num) {
  300.         return preg_match('@^[0-9]+$@', $num, $m);
  301. }
  302.  
  303. function _decode_aid($aid) {
  304.  
  305.         // based on https://github.com/thephpleague/iso3166/blob/main/src/ISO3166.php
  306.         // commit 26 July 2022
  307.         // Generated using:
  308.         /*
  309.         $x = new ISO3166();
  310.         $bla = $x->all();
  311.         foreach ($bla as $data) {
  312.                 $out[] = "\t\$iso3166['".$data['numeric']."'] = \"".$data['name']."\";\n";
  313.         }
  314.         */
  315.         $iso3166['004'] = "Afghanistan";
  316.         $iso3166['248'] = "Ã…land Islands";
  317.         $iso3166['008'] = "Albania";
  318.         $iso3166['012'] = "Algeria";
  319.         $iso3166['016'] = "American Samoa";
  320.         $iso3166['020'] = "Andorra";
  321.         $iso3166['024'] = "Angola";
  322.         $iso3166['660'] = "Anguilla";
  323.         $iso3166['010'] = "Antarctica";
  324.         $iso3166['028'] = "Antigua and Barbuda";
  325.         $iso3166['032'] = "Argentina";
  326.         $iso3166['051'] = "Armenia";
  327.         $iso3166['533'] = "Aruba";
  328.         $iso3166['036'] = "Australia";
  329.         $iso3166['040'] = "Austria";
  330.         $iso3166['031'] = "Azerbaijan";
  331.         $iso3166['044'] = "Bahamas";
  332.         $iso3166['048'] = "Bahrain";
  333.         $iso3166['050'] = "Bangladesh";
  334.         $iso3166['052'] = "Barbados";
  335.         $iso3166['112'] = "Belarus";
  336.         $iso3166['056'] = "Belgium";
  337.         $iso3166['084'] = "Belize";
  338.         $iso3166['204'] = "Benin";
  339.         $iso3166['060'] = "Bermuda";
  340.         $iso3166['064'] = "Bhutan";
  341.         $iso3166['068'] = "Bolivia (Plurinational State of)";
  342.         $iso3166['535'] = "Bonaire, Sint Eustatius and Saba";
  343.         $iso3166['070'] = "Bosnia and Herzegovina";
  344.         $iso3166['072'] = "Botswana";
  345.         $iso3166['074'] = "Bouvet Island";
  346.         $iso3166['076'] = "Brazil";
  347.         $iso3166['086'] = "British Indian Ocean Territory";
  348.         $iso3166['096'] = "Brunei Darussalam";
  349.         $iso3166['100'] = "Bulgaria";
  350.         $iso3166['854'] = "Burkina Faso";
  351.         $iso3166['108'] = "Burundi";
  352.         $iso3166['132'] = "Cabo Verde";
  353.         $iso3166['116'] = "Cambodia";
  354.         $iso3166['120'] = "Cameroon";
  355.         $iso3166['124'] = "Canada";
  356.         $iso3166['136'] = "Cayman Islands";
  357.         $iso3166['140'] = "Central African Republic";
  358.         $iso3166['148'] = "Chad";
  359.         $iso3166['152'] = "Chile";
  360.         $iso3166['156'] = "China";
  361.         $iso3166['162'] = "Christmas Island";
  362.         $iso3166['166'] = "Cocos (Keeling) Islands";
  363.         $iso3166['170'] = "Colombia";
  364.         $iso3166['174'] = "Comoros";
  365.         $iso3166['178'] = "Congo";
  366.         $iso3166['180'] = "Congo (Democratic Republic of the)";
  367.         $iso3166['184'] = "Cook Islands";
  368.         $iso3166['188'] = "Costa Rica";
  369.         $iso3166['384'] = "Côte d'Ivoire";
  370.         $iso3166['191'] = "Croatia";
  371.         $iso3166['192'] = "Cuba";
  372.         $iso3166['531'] = "Curaçao";
  373.         $iso3166['196'] = "Cyprus";
  374.         $iso3166['203'] = "Czechia";
  375.         $iso3166['208'] = "Denmark";
  376.         $iso3166['262'] = "Djibouti";
  377.         $iso3166['212'] = "Dominica";
  378.         $iso3166['214'] = "Dominican Republic";
  379.         $iso3166['218'] = "Ecuador";
  380.         $iso3166['818'] = "Egypt";
  381.         $iso3166['222'] = "El Salvador";
  382.         $iso3166['226'] = "Equatorial Guinea";
  383.         $iso3166['232'] = "Eritrea";
  384.         $iso3166['233'] = "Estonia";
  385.         $iso3166['231'] = "Ethiopia";
  386.         $iso3166['748'] = "Eswatini";
  387.         $iso3166['238'] = "Falkland Islands (Malvinas)";
  388.         $iso3166['234'] = "Faroe Islands";
  389.         $iso3166['242'] = "Fiji";
  390.         $iso3166['246'] = "Finland";
  391.         $iso3166['250'] = "France";
  392.         $iso3166['254'] = "French Guiana";
  393.         $iso3166['258'] = "French Polynesia";
  394.         $iso3166['260'] = "French Southern Territories";
  395.         $iso3166['266'] = "Gabon";
  396.         $iso3166['270'] = "Gambia";
  397.         $iso3166['268'] = "Georgia";
  398.         $iso3166['276'] = "Germany";
  399.         $iso3166['288'] = "Ghana";
  400.         $iso3166['292'] = "Gibraltar";
  401.         $iso3166['300'] = "Greece";
  402.         $iso3166['304'] = "Greenland";
  403.         $iso3166['308'] = "Grenada";
  404.         $iso3166['312'] = "Guadeloupe";
  405.         $iso3166['316'] = "Guam";
  406.         $iso3166['320'] = "Guatemala";
  407.         $iso3166['831'] = "Guernsey";
  408.         $iso3166['324'] = "Guinea";
  409.         $iso3166['624'] = "Guinea-Bissau";
  410.         $iso3166['328'] = "Guyana";
  411.         $iso3166['332'] = "Haiti";
  412.         $iso3166['334'] = "Heard Island and McDonald Islands";
  413.         $iso3166['336'] = "Holy See";
  414.         $iso3166['340'] = "Honduras";
  415.         $iso3166['344'] = "Hong Kong";
  416.         $iso3166['348'] = "Hungary";
  417.         $iso3166['352'] = "Iceland";
  418.         $iso3166['356'] = "India";
  419.         $iso3166['360'] = "Indonesia";
  420.         $iso3166['364'] = "Iran (Islamic Republic of)";
  421.         $iso3166['368'] = "Iraq";
  422.         $iso3166['372'] = "Ireland";
  423.         $iso3166['833'] = "Isle of Man";
  424.         $iso3166['376'] = "Israel";
  425.         $iso3166['380'] = "Italy";
  426.         $iso3166['388'] = "Jamaica";
  427.         $iso3166['392'] = "Japan";
  428.         $iso3166['832'] = "Jersey";
  429.         $iso3166['400'] = "Jordan";
  430.         $iso3166['398'] = "Kazakhstan";
  431.         $iso3166['404'] = "Kenya";
  432.         $iso3166['296'] = "Kiribati";
  433.         $iso3166['408'] = "Korea (Democratic People's Republic of)";
  434.         $iso3166['410'] = "Korea (Republic of)";
  435.         $iso3166['414'] = "Kuwait";
  436.         $iso3166['417'] = "Kyrgyzstan";
  437.         $iso3166['418'] = "Lao People's Democratic Republic";
  438.         $iso3166['428'] = "Latvia";
  439.         $iso3166['422'] = "Lebanon";
  440.         $iso3166['426'] = "Lesotho";
  441.         $iso3166['430'] = "Liberia";
  442.         $iso3166['434'] = "Libya";
  443.         $iso3166['438'] = "Liechtenstein";
  444.         $iso3166['440'] = "Lithuania";
  445.         $iso3166['442'] = "Luxembourg";
  446.         $iso3166['446'] = "Macao";
  447.         $iso3166['807'] = "North Macedonia";
  448.         $iso3166['450'] = "Madagascar";
  449.         $iso3166['454'] = "Malawi";
  450.         $iso3166['458'] = "Malaysia";
  451.         $iso3166['462'] = "Maldives";
  452.         $iso3166['466'] = "Mali";
  453.         $iso3166['470'] = "Malta";
  454.         $iso3166['584'] = "Marshall Islands";
  455.         $iso3166['474'] = "Martinique";
  456.         $iso3166['478'] = "Mauritania";
  457.         $iso3166['480'] = "Mauritius";
  458.         $iso3166['175'] = "Mayotte";
  459.         $iso3166['484'] = "Mexico";
  460.         $iso3166['583'] = "Micronesia (Federated States of)";
  461.         $iso3166['498'] = "Moldova (Republic of)";
  462.         $iso3166['492'] = "Monaco";
  463.         $iso3166['496'] = "Mongolia";
  464.         $iso3166['499'] = "Montenegro";
  465.         $iso3166['500'] = "Montserrat";
  466.         $iso3166['504'] = "Morocco";
  467.         $iso3166['508'] = "Mozambique";
  468.         $iso3166['104'] = "Myanmar";
  469.         $iso3166['516'] = "Namibia";
  470.         $iso3166['520'] = "Nauru";
  471.         $iso3166['524'] = "Nepal";
  472.         $iso3166['528'] = "Netherlands";
  473.         $iso3166['540'] = "New Caledonia";
  474.         $iso3166['554'] = "New Zealand";
  475.         $iso3166['558'] = "Nicaragua";
  476.         $iso3166['562'] = "Niger";
  477.         $iso3166['566'] = "Nigeria";
  478.         $iso3166['570'] = "Niue";
  479.         $iso3166['574'] = "Norfolk Island";
  480.         $iso3166['580'] = "Northern Mariana Islands";
  481.         $iso3166['578'] = "Norway";
  482.         $iso3166['512'] = "Oman";
  483.         $iso3166['586'] = "Pakistan";
  484.         $iso3166['585'] = "Palau";
  485.         $iso3166['275'] = "Palestine, State of";
  486.         $iso3166['591'] = "Panama";
  487.         $iso3166['598'] = "Papua New Guinea";
  488.         $iso3166['600'] = "Paraguay";
  489.         $iso3166['604'] = "Peru";
  490.         $iso3166['608'] = "Philippines";
  491.         $iso3166['612'] = "Pitcairn";
  492.         $iso3166['616'] = "Poland";
  493.         $iso3166['620'] = "Portugal";
  494.         $iso3166['630'] = "Puerto Rico";
  495.         $iso3166['634'] = "Qatar";
  496.         $iso3166['638'] = "Réunion";
  497.         $iso3166['642'] = "Romania";
  498.         $iso3166['643'] = "Russian Federation";
  499.         $iso3166['646'] = "Rwanda";
  500.         $iso3166['652'] = "Saint Barthélemy";
  501.         $iso3166['654'] = "Saint Helena, Ascension and Tristan da Cunha";
  502.         $iso3166['659'] = "Saint Kitts and Nevis";
  503.         $iso3166['662'] = "Saint Lucia";
  504.         $iso3166['663'] = "Saint Martin (French part)";
  505.         $iso3166['666'] = "Saint Pierre and Miquelon";
  506.         $iso3166['670'] = "Saint Vincent and the Grenadines";
  507.         $iso3166['882'] = "Samoa";
  508.         $iso3166['674'] = "San Marino";
  509.         $iso3166['678'] = "Sao Tome and Principe";
  510.         $iso3166['682'] = "Saudi Arabia";
  511.         $iso3166['686'] = "Senegal";
  512.         $iso3166['688'] = "Serbia";
  513.         $iso3166['690'] = "Seychelles";
  514.         $iso3166['694'] = "Sierra Leone";
  515.         $iso3166['702'] = "Singapore";
  516.         $iso3166['534'] = "Sint Maarten (Dutch part)";
  517.         $iso3166['703'] = "Slovakia";
  518.         $iso3166['705'] = "Slovenia";
  519.         $iso3166['090'] = "Solomon Islands";
  520.         $iso3166['706'] = "Somalia";
  521.         $iso3166['710'] = "South Africa";
  522.         $iso3166['239'] = "South Georgia and the South Sandwich Islands";
  523.         $iso3166['728'] = "South Sudan";
  524.         $iso3166['724'] = "Spain";
  525.         $iso3166['144'] = "Sri Lanka";
  526.         $iso3166['729'] = "Sudan";
  527.         $iso3166['740'] = "Suriname";
  528.         $iso3166['744'] = "Svalbard and Jan Mayen";
  529.         $iso3166['752'] = "Sweden";
  530.         $iso3166['756'] = "Switzerland";
  531.         $iso3166['760'] = "Syrian Arab Republic";
  532.         $iso3166['158'] = "Taiwan (Province of China)";
  533.         $iso3166['762'] = "Tajikistan";
  534.         $iso3166['834'] = "Tanzania, United Republic of";
  535.         $iso3166['764'] = "Thailand";
  536.         $iso3166['626'] = "Timor-Leste";
  537.         $iso3166['768'] = "Togo";
  538.         $iso3166['772'] = "Tokelau";
  539.         $iso3166['776'] = "Tonga";
  540.         $iso3166['780'] = "Trinidad and Tobago";
  541.         $iso3166['788'] = "Tunisia";
  542.         $iso3166['792'] = "Turkey";
  543.         $iso3166['795'] = "Turkmenistan";
  544.         $iso3166['796'] = "Turks and Caicos Islands";
  545.         $iso3166['798'] = "Tuvalu";
  546.         $iso3166['800'] = "Uganda";
  547.         $iso3166['804'] = "Ukraine";
  548.         $iso3166['784'] = "United Arab Emirates";
  549.         $iso3166['826'] = "United Kingdom of Great Britain and Northern Ireland";
  550.         $iso3166['840'] = "United States of America";
  551.         $iso3166['581'] = "United States Minor Outlying Islands";
  552.         $iso3166['858'] = "Uruguay";
  553.         $iso3166['860'] = "Uzbekistan";
  554.         $iso3166['548'] = "Vanuatu";
  555.         $iso3166['862'] = "Venezuela (Bolivarian Republic of)";
  556.         $iso3166['704'] = "Viet Nam";
  557.         $iso3166['092'] = "Virgin Islands (British)";
  558.         $iso3166['850'] = "Virgin Islands (U.S.)";
  559.         $iso3166['876'] = "Wallis and Futuna";
  560.         $iso3166['732'] = "Western Sahara";
  561.         $iso3166['887'] = "Yemen";
  562.         $iso3166['894'] = "Zambia";
  563.         $iso3166['716'] = "Zimbabwe";
  564.  
  565.         $out = array();
  566.  
  567.         $aid = strtoupper($aid);
  568.         $aid = trim($aid);
  569.         $aid = str_replace(' ','',$aid);
  570.         $aid = str_replace(':','',$aid);
  571.  
  572.         if ($aid == '') {
  573.                 $out[] = "INVALID: The AID is empty";
  574.                 return $out;
  575.         }
  576.  
  577.         if (!preg_match('@^[0-9A-F]+$@', $aid, $m)) {
  578.                 $out[] = "INVALID: AID has invalid characters. Only A..F and 0..9 are allowed";
  579.                 return $out;
  580.         }
  581.  
  582.         $aid_hf = implode(':',str_split($aid,2));
  583.         if (strlen($aid)%2 == 1) $aid_hf .= '_';
  584.  
  585.         $out[] = array("$aid", "ISO/IEC 7816 Application Identifier (AID)");
  586.         $out[] = array('', "> $aid_hf <");
  587.         $out[] = array('', c_literal_hexstr($aid));
  588.  
  589.         if ((strlen($aid) == 32) && (substr($aid,-2) == 'FF')) {
  590.                 // Sometimes you read that a 16-byte AID must not end with FF, because it is reserved by ISO.
  591.                 // I have only found one official source:
  592.                 // ISO/IEC 7816-5 : 1994
  593.                 //        Identification cards - Integrated circuit(s) cards with contacts -
  594.                 //        Part 5 : Numbering system and registration procedure for application identifiers
  595.                 //        https://cdn.standards.iteh.ai/samples/19980/8ff6c7ccc9254fe4b7a8a21c0bf59424/ISO-IEC-7816-5-1994.pdf
  596.                 // Quote from clause 5.2:
  597.                 //       "The PIX has a free coding. If the AID is 16 bytes long,
  598.                 //        then the value 'FF' for the least significant byte is reserved for future use."
  599.                 // In the revisions of ISO/IEC 7816, parts of ISO 7816-5 (e.g. the AID categories)
  600.                 // have been moved to ISO 7816-4.
  601.                 // The "FF" reservation cannot be found in modern versions of 7816-4 or 7816-5.
  602.                 /*$out[] = array('',"INVALID: A 16-byte AID must not end with FF. (Reserved by ISO/IEC)");*/
  603.                 $out[] = array('',"Note: A 16-byte AID ending with FF was reserved by ISO/IEC 7816-5:1994");
  604.         }
  605.  
  606.         if (strlen($aid) > 32) {
  607.                 $out[] = array('',"INVALID: An AID must not be longer than 16 bytes");
  608.         }
  609.  
  610.         $category = substr($aid,0,1);
  611.  
  612.         // Category 0..9
  613.         // RID = ISO/IEC 7812 Issuer Identification Number (IIN 6 or 8 digits)
  614.         // AID = RID + 'FF' + PIX
  615.         $iso7812_category = array();
  616.         $iso7812_category['0'] = 'ISO/TC 68 and other industry assignments';
  617.         $iso7812_category['1'] = 'Airlines';
  618.         $iso7812_category['2'] = 'Airlines, financial and other future industry assignments';
  619.         $iso7812_category['3'] = 'Travel and entertainment';
  620.         $iso7812_category['4'] = 'Banking and financial';
  621.         $iso7812_category['5'] = 'Banking and financial';
  622.         $iso7812_category['6'] = 'Merchandising and banking/financial';
  623.         $iso7812_category['7'] = 'Petroleum and other future industry assignments';
  624.         $iso7812_category['8'] = 'Healthcare, telecommunications and other future industry assignments';
  625.         $iso7812_category['9'] = 'Assignment by national standards bodies';
  626.         foreach ($iso7812_category as $check_cat => $check_cat_name) {
  627.                 if ("$category" == "$check_cat") { // comparison as string is important so that "===" works. "==" does not work because 0=='A' for some reason!
  628.                         #$out[] = array($category, "AID based on category $category of ISO/IEC 7812 Issuer Identification Number (IIN)");
  629.                         #$out[] = array('',        "($check_cat = $check_cat_name)");
  630.                         $out[] = array('', "AID based on ISO/IEC 7812 Issuer Identification Number (IIN)");
  631.  
  632.                         $iin = $aid;
  633.                         // IIN and PIX must be delimited with FF, but only if a PIX is available.
  634.                         // When the IIN has an odd number, then an extra 'F' must be added at the end
  635.                         $pos = strpos($aid,'F');
  636.                         if ($pos !== false) $iin = substr($iin, 0, $pos);
  637.  
  638.                         if (!_is_bcd($iin)) {
  639.                                 $out[] = array($iin, "INVALID: Expected BCD encoded IIN, optionally followed by FF and PIX");
  640.                                 return $out;
  641.                         }
  642.  
  643.                         $pad = '';
  644.  
  645.                         $out[] = 'RID-HERE'; // will (must) be replaced below
  646.  
  647.                         $out[] = array($iin, "ISO/IEC 7812 Issuer Identification Number (IIN)");
  648.                         if ((strlen($iin) != 6) && (strlen($iin) != 8)) {
  649.                                 $out[] = array('',"Warning: IIN has an unusual length. 6 or 8 digits are expected!");
  650.                         }
  651.  
  652.                         $out[] = array($category, "Major industry identifier $category = $check_cat_name");
  653.                         $pad .= str_repeat(' ', strlen("$category"));
  654.  
  655.                         if ("$category" === "9") {
  656.                                 $country = substr($iin,1,3);
  657.                                 if ($country == '') {
  658.                                         $out[] = array($pad.'___', 'ISO/IEC 3166-1 Numeric Country code (missing)');
  659.                                 } else {
  660.                                         $country_name = isset($iso3166[$country]) ? $iso3166[$country] : 'Unknown country';
  661.                                         $out[] = array($pad.str_pad($country,3,'_',STR_PAD_RIGHT), "ISO/IEC 3166-1 Numeric Country code : $country ($country_name)");
  662.                                 }
  663.                                 $pad .= '   ';
  664.                                 $asi = substr($iin,4);
  665.                                 $asn = $asi;
  666.                         } else {
  667.                                 $asi = substr($iin,1);
  668.                                 $asn = $asi;
  669.                         }
  670.                         $out[] = array("$pad$asn", 'Assigned number'.($asi=='' ? ' (missing)' : ''));
  671.                         if ($asi!='') $out[] = array('', c_literal_hexstr($asi));
  672.                         $pad .= str_repeat(' ',strlen($asn));
  673.  
  674.                         $padded_iin = $iin;
  675.                         if (strlen($iin)%2 != 0) {
  676.                                 $odd_padding = substr($aid,strlen($iin),1);
  677.                                 if ($odd_padding != 'F') {
  678.                                         foreach ($out as $n => &$tmp) {
  679.                                                 if ($tmp == 'RID-HERE') {
  680.                                                         unset($out[$n]);
  681.                                                         break;
  682.                                                 }
  683.                                         }
  684.                                         $out[] = array("$pad!","INVALID: An IIN with odd length must be padded with F, e.g. 123 => 123F");
  685.                                         return $out;
  686.                                 }
  687.                                 $out[] = array($pad.$odd_padding, 'Padding of IIN with odd length');
  688.                                 $padded_iin .= $odd_padding;
  689.                                 $pad .= ' ';
  690.                         }
  691.  
  692.                         $rid = $padded_iin;
  693.                         foreach ($out as &$tmp) {
  694.                                 if ($tmp == 'RID-HERE') {
  695.                                         $tmp = array("$rid", "Registered Application Provider Identifier (RID)");
  696.                                         break;
  697.                                 }
  698.                         }
  699.  
  700.                         if (strlen($aid) == strlen($padded_iin)) {
  701.                                 // There is no PIX
  702.                                 $out[] = "Proprietary application identifier extension (PIX) missing";
  703.                         } else {
  704.                                 $delimiter = substr($aid,strlen($padded_iin),2);
  705.                                 if ($delimiter != 'FF') {
  706.                                         $out[] = array($pad.substr($aid,strlen($padded_iin)), "INVALID: RID/IIN and PIX must be delimited by FF");
  707.                                         return $out;
  708.                                 }
  709.                                 $out[] = array($pad.$delimiter, 'Delimiter which separates RID/IIN from PIX');
  710.                                 $pad .= str_repeat(' ',strlen($delimiter));
  711.  
  712.                                 $pix = substr($aid,strlen($padded_iin)+strlen('FF'));
  713.                                 if ($pix == '') {
  714.                                         $out[] = "Proprietary application identifier extension (PIX) missing";
  715.                                         $out[] = "Warning: If PIX is available, FF delimites RID/IIN from PIX. Since PIX is empty, consider removing FF."; // not sure if this is an error or not
  716.                                 } else {
  717.                                         $out[] = array($pad.$pix, "Proprietary application identifier extension (PIX)");
  718.                                         $out[] = array('', c_literal_hexstr($pix));
  719.                                 }
  720.                         }
  721.  
  722.                         return $out;
  723.                 }
  724.         }
  725.  
  726.         // Category 'A' (International Registration)
  727.         // RID = 'A' + 9 digits
  728.         // AID = RID + PIX
  729.         if ("$category" === "A") {
  730.                 $rid = substr($aid,0,10);
  731.                 $rid = str_pad($rid,10,'_',STR_PAD_RIGHT);
  732.  
  733.                 $pix = substr($aid,10);
  734.  
  735.                 $asi = substr($aid,1,9);
  736.                 $asn = str_pad($asi,9,'_',STR_PAD_RIGHT);
  737.  
  738.                 $out[] = array("$rid", "Registered Application Provider Identifier (RID)");
  739.                 $out[] = array("$category", "Category $category: International registration");
  740.                 $out[] = array(" $asn", 'Assigned number, BCD recommended'.($asi=='' ? ' (missing)' : ''));
  741.                 if ($asi!='') $out[] = array('', c_literal_hexstr($asi));
  742.                 if ($pix == '') {
  743.                         $out[] = "Proprietary application identifier extension (PIX) missing";
  744.                 } else {
  745.                         $out[] = array(str_pad($pix,strlen($aid),' ',STR_PAD_LEFT), "Proprietary application identifier extension (PIX)");
  746.                         $out[] = array('', c_literal_hexstr($pix));
  747.                 }
  748.  
  749.                 return $out;
  750.         }
  751.  
  752.         // Category 'D' (Local/National Registration)
  753.         // RID = 'D' + 3 digits country code (ISO/IEC 3166-1) + 6 digits
  754.         // AID = RID + PIX
  755.         if ("$category" === "D") {
  756.                 $rid = substr($aid,0,10);
  757.                 $rid = str_pad($rid,10,'_',STR_PAD_RIGHT);
  758.  
  759.                 $pix = substr($aid,10);
  760.  
  761.                 $country = substr($aid,1,3);
  762.  
  763.                 $asi = substr($aid,4,6);
  764.                 $asn = str_pad($asi,6,'_',STR_PAD_RIGHT);
  765.  
  766.                 $out[] = array("$rid", "Registered Application Provider Identifier (RID)");
  767.                 $out[] = array("$category", "Category $category: Local/National registration");
  768.                 if ($country == '') {
  769.                         $out[] = array(" ___", "ISO/IEC 3166-1 Numeric Country code (missing)");
  770.                 } else {
  771.                         $country_name = isset($iso3166[$country]) ? $iso3166[$country] : 'Unknown country';
  772.                         $out[] = array(" ".str_pad($country,3,'_',STR_PAD_RIGHT), "ISO/IEC 3166-1 Numeric Country code : $country ($country_name)");
  773.                 }
  774.                 $out[] = array("    $asn", 'Assigned number, BCD recommended'.($asi=='' ? ' (missing)' : ''));
  775.                 if ($asi!='') $out[] = array('', c_literal_hexstr($asi));
  776.                 if ($pix == '') {
  777.                         $out[] = "Proprietary application identifier extension (PIX) missing";
  778.                 } else {
  779.                         $out[] = array(str_pad($pix,strlen($aid),' ',STR_PAD_LEFT), "Proprietary application identifier extension (PIX)");
  780.                         $out[] = array('', c_literal_hexstr($pix));
  781.                 }
  782.  
  783.                 return $out;
  784.         }
  785.  
  786.         // Category 'E'
  787.         // AID = 'E8' + OID + PIX   (OID is DER encoding without type and length)
  788.         if ("$category" === "E") {
  789.                 $out[] = array("$category", "Category $category: Standard");
  790.  
  791.                 $std_schema = substr($aid,1,1);
  792.                 if ($std_schema == '8') {
  793.                         $out[] = array(" $std_schema", "Standard identified by OID");
  794.  
  795.                         // Start: Try to find out if it is E8+Length+OID (inofficial/illegal) or E8+OID (ISO)
  796.                         $len_usage = _aid_e8_length_usage($aid);
  797.                         $include_der_length = true; // In case it is ambiguous , let's say it is E8+Length+OID
  798.                                                     // Note that these ambiguous are rare and will only happen inside the root OID 0
  799.                         if ($len_usage === true)  $include_der_length = true;
  800.                         if ($len_usage === false) $include_der_length = false;
  801.                         if ($include_der_length) {
  802.                                 // Case E8+Length+OID (inofficial/illegal)
  803.                                 $der_length_hex = substr($aid,2,2);
  804.                                 $der_length_dec = hexdec($der_length_hex);
  805.                                 $out[] = array("  $der_length_hex", "DER encoding length (illegal usage not defined by ISO)");
  806.                                 $pure_der = substr($aid,4);
  807.                                 $indent = 4;
  808.                                 $e8_minmax_measure = 'DER';
  809.                                 $e8_min = $der_length_dec;
  810.                                 $e8_max = $der_length_dec;
  811.                         } else {
  812.                                 // Case E8+OID (defined by ISO, but only for their 1.0 OID)
  813.                                 $pure_der = substr($aid,2);
  814.                                 $indent = 2;
  815.                                 if (substr($aid,2,2) == '28') { // '28' = OID 1.0 (ISO Standard)
  816.                                         // ISO Standards (OID 1.0) will only have 1 or 2 numbers. (Number 1 is the standard, and number 2
  817.                                         // is the part in case of a multi-part standard).
  818.                                         $e8_minmax_measure = 'ARC';
  819.                                         $e8_min = 3; // 1.0.aaaa   (ISO AAAA)
  820.                                         $e8_max = 4; // 1.0.aaaa.b (ISO AAAA-B)
  821.                                 } else {
  822.                                         // This is the inofficial usage of E8+OID, i.e. using an OID outside of arc 1.0
  823.                                         $e8_minmax_measure = 'ARC';
  824.                                         $e8_min = 2;  // At least 2 arcs (OID x.y)
  825.                                         $e8_max = -1; // no limit
  826.                                 }
  827.                         }
  828.                         // End: Try to find out if it is E8+Length+OID (inofficial/illegal) or E8+OID (ISO)
  829.  
  830.                         try {
  831.                                 $interpretations = _aid_e8_interpretations($pure_der,$e8_minmax_measure,$e8_min,$e8_max);
  832.                                 foreach ($interpretations as $ii => $interpretation) {
  833.                                         $pos = $interpretation[0];
  834.                                         $txt1 = $interpretation[1]; // Standard
  835.                                         $txt2 = $interpretation[2]; // PIX (optional)
  836.  
  837.                                         $aid1 = str_repeat(' ',$indent).substr($pure_der,0,$pos*2);
  838.                                         $aid2 = substr($pure_der,$pos*2);
  839.  
  840.                                         $out[] = array("$aid1", "$txt1");
  841.                                         if ($txt2 !== '') {
  842.                                                 $pix = "$txt2 (".c_literal_hexstr(str_replace(':','',$txt2)).")";
  843.                                                 $out[] = array(str_repeat(' ',strlen($aid1))."$aid2", "with PIX $pix");
  844.                                         }
  845.                                         if ($ii < count($interpretations)-1) {
  846.                                                 $out[] = array('', 'or:');
  847.                                         }
  848.                                 }
  849.                         } catch (Exception $e) {
  850.                                 $out[] = array(str_repeat(' ',$indent).$pure_der, "ERROR: ".$e->getMessage());
  851.                         }
  852.                 } else if ($std_schema != '') {
  853.                         // E0..E7, E9..EF are RFU
  854.                         $unknown = substr($aid,1);
  855.                         $out[] = array(" $unknown", "ILLEGAL USAGE / RESERVED");
  856.                 }
  857.  
  858.                 return $out;
  859.         }
  860.  
  861.         // Category 'F'
  862.         // AID = 'F' + PIX
  863.         if ("$category" === "F") {
  864.                 $out[] = array("$category", "Category $category: Non-registered / Proprietary");
  865.                 $rid = substr($aid,0,1);
  866.                 $pix = substr($aid,1);
  867.                 if ($pix == '') {
  868.                         $out[] = "Proprietary application identifier extension (PIX) missing";
  869.                 } else {
  870.                         $out[] = array(' '.$pix, "Proprietary application identifier extension (PIX)");
  871.                         $out[] = array('', c_literal_hexstr($pix));
  872.                 }
  873.                 return $out;
  874.         }
  875.  
  876.         // Category 'B' and 'C' are reserved
  877.         $out[] = array("$category", "Category $category: ILLEGAL USAGE / RESERVED");
  878.         if (strlen($aid) > 1) {
  879.                 $aid_ = substr($aid,1);
  880.                 $out[] = array(" ".$aid_, "Unknown composition");
  881.                 $out[] = array('', c_literal_hexstr($aid_));
  882.         }
  883.         return $out;
  884. }
  885.  
  886. /* --- Small extra function: not part of the decoder --- */
  887.  
  888. function aid_split_rid_pix($a, &$rid=null, &$pix=null) {
  889.         // "Quick'n'Dirty" function which does not do any consistency checks!
  890.         // It expects that the string is a valid AID!
  891.  
  892.         $cat = substr($a,0,1);
  893.         if (is_numeric($cat)) {
  894.                 $p = strpos($a,'F');
  895.                 if ($p%2 != 0) $p++;
  896.         } else if (($cat == 'A') || ($cat == 'D')) {
  897.                 $p = 10;
  898.         } else if ($cat == 'F') {
  899.                 $p = 1;
  900.         } else {
  901.                 $p = 0;
  902.         }
  903.  
  904.         if ($rid !== null) $rid = substr($a, 0, $p);
  905.         if ($pix !== null) $pix = substr($a, $p);
  906.  
  907.         return $p;
  908. }
  909.  
  910. function aid_canonize(&$aid_candidate) {
  911.         $aid_candidate = str_replace(' ', '', $aid_candidate);
  912.         $aid_candidate = str_replace(':', '', $aid_candidate);
  913.         $aid_candidate = strtoupper($aid_candidate);
  914.         if (strlen($aid_candidate) > 16*2) {
  915.                 $aid_is_ok = false; // OID DER encoding is too long to fit into the AID
  916.         } else if ((strlen($aid_candidate) == 16*2) && (substr($aid_candidate,-2) == 'FF')) {
  917.                 $aid_is_ok = false; // 16 byte AID must not end with 0xFF (reserved by ISO)
  918.         } else {
  919.                 $aid_is_ok = true;
  920.         }
  921.         return $aid_is_ok;
  922. }
  923.