Subversion Repositories php_utils

Rev

Rev 44 | Rev 46 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

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