Subversion Repositories oidplus

Rev

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

  1. <?php
  2.  
  3. /**
  4.  * Pure-PHP ASN.1 Parser
  5.  *
  6.  * PHP version 5
  7.  *
  8.  * ASN.1 provides the semantics for data encoded using various schemes.  The most commonly
  9.  * utilized scheme is DER or the "Distinguished Encoding Rules".  PEM's are base64 encoded
  10.  * DER blobs.
  11.  *
  12.  * \phpseclib3\File\ASN1 decodes and encodes DER formatted messages and places them in a semantic context.
  13.  *
  14.  * Uses the 1988 ASN.1 syntax.
  15.  *
  16.  * @author    Jim Wigginton <terrafrost@php.net>
  17.  * @copyright 2012 Jim Wigginton
  18.  * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
  19.  * @link      http://phpseclib.sourceforge.net
  20.  */
  21.  
  22. namespace phpseclib3\File;
  23.  
  24. use DateTime;
  25. use phpseclib3\Common\Functions\Strings;
  26. use phpseclib3\File\ASN1\Element;
  27. use phpseclib3\Math\BigInteger;
  28.  
  29. /**
  30.  * Pure-PHP ASN.1 Parser
  31.  *
  32.  * @author  Jim Wigginton <terrafrost@php.net>
  33.  */
  34. abstract class ASN1
  35. {
  36.     // Tag Classes
  37.     // http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=12
  38.     const CLASS_UNIVERSAL        = 0;
  39.     const CLASS_APPLICATION      = 1;
  40.     const CLASS_CONTEXT_SPECIFIC = 2;
  41.     const CLASS_PRIVATE          = 3;
  42.  
  43.     // Tag Classes
  44.     // http://www.obj-sys.com/asn1tutorial/node124.html
  45.     const TYPE_BOOLEAN           = 1;
  46.     const TYPE_INTEGER           = 2;
  47.     const TYPE_BIT_STRING        = 3;
  48.     const TYPE_OCTET_STRING      = 4;
  49.     const TYPE_NULL              = 5;
  50.     const TYPE_OBJECT_IDENTIFIER = 6;
  51.     //const TYPE_OBJECT_DESCRIPTOR = 7;
  52.     //const TYPE_INSTANCE_OF       = 8; // EXTERNAL
  53.     const TYPE_REAL              = 9;
  54.     const TYPE_ENUMERATED        = 10;
  55.     //const TYPE_EMBEDDED          = 11;
  56.     const TYPE_UTF8_STRING       = 12;
  57.     //const TYPE_RELATIVE_OID      = 13;
  58.     const TYPE_SEQUENCE          = 16; // SEQUENCE OF
  59.     const TYPE_SET               = 17; // SET OF
  60.  
  61.     // More Tag Classes
  62.     // http://www.obj-sys.com/asn1tutorial/node10.html
  63.     const TYPE_NUMERIC_STRING   = 18;
  64.     const TYPE_PRINTABLE_STRING = 19;
  65.     const TYPE_TELETEX_STRING   = 20; // T61String
  66.     const TYPE_VIDEOTEX_STRING  = 21;
  67.     const TYPE_IA5_STRING       = 22;
  68.     const TYPE_UTC_TIME         = 23;
  69.     const TYPE_GENERALIZED_TIME = 24;
  70.     const TYPE_GRAPHIC_STRING   = 25;
  71.     const TYPE_VISIBLE_STRING   = 26; // ISO646String
  72.     const TYPE_GENERAL_STRING   = 27;
  73.     const TYPE_UNIVERSAL_STRING = 28;
  74.     //const TYPE_CHARACTER_STRING = 29;
  75.     const TYPE_BMP_STRING       = 30;
  76.  
  77.     // Tag Aliases
  78.     // These tags are kinda place holders for other tags.
  79.     const TYPE_CHOICE = -1;
  80.     const TYPE_ANY    = -2;
  81.  
  82.     /**
  83.      * ASN.1 object identifiers
  84.      *
  85.      * @var array
  86.      * @link http://en.wikipedia.org/wiki/Object_identifier
  87.      */
  88.     private static $oids = [];
  89.  
  90.     /**
  91.      * ASN.1 object identifier reverse mapping
  92.      *
  93.      * @var array
  94.      */
  95.     private static $reverseOIDs = [];
  96.  
  97.     /**
  98.      * Default date format
  99.      *
  100.      * @var string
  101.      * @link http://php.net/class.datetime
  102.      */
  103.     private static $format = 'D, d M Y H:i:s O';
  104.  
  105.     /**
  106.      * Filters
  107.      *
  108.      * If the mapping type is self::TYPE_ANY what do we actually encode it as?
  109.      *
  110.      * @var array
  111.      * @see self::encode_der()
  112.      */
  113.     private static $filters;
  114.  
  115.     /**
  116.      * Current Location of most recent ASN.1 encode process
  117.      *
  118.      * Useful for debug purposes
  119.      *
  120.      * @var array
  121.      * @see self::encode_der()
  122.      */
  123.     private static $location;
  124.  
  125.     /**
  126.      * DER Encoded String
  127.      *
  128.      * In case we need to create ASN1\Element object's..
  129.      *
  130.      * @var string
  131.      * @see self::decodeDER()
  132.      */
  133.     private static $encoded;
  134.  
  135.     /**
  136.      * Type mapping table for the ANY type.
  137.      *
  138.      * Structured or unknown types are mapped to a \phpseclib3\File\ASN1\Element.
  139.      * Unambiguous types get the direct mapping (int/real/bool).
  140.      * Others are mapped as a choice, with an extra indexing level.
  141.      *
  142.      * @var array
  143.      */
  144.     const ANY_MAP = [
  145.         self::TYPE_BOOLEAN              => true,
  146.         self::TYPE_INTEGER              => true,
  147.         self::TYPE_BIT_STRING           => 'bitString',
  148.         self::TYPE_OCTET_STRING         => 'octetString',
  149.         self::TYPE_NULL                 => 'null',
  150.         self::TYPE_OBJECT_IDENTIFIER    => 'objectIdentifier',
  151.         self::TYPE_REAL                 => true,
  152.         self::TYPE_ENUMERATED           => 'enumerated',
  153.         self::TYPE_UTF8_STRING          => 'utf8String',
  154.         self::TYPE_NUMERIC_STRING       => 'numericString',
  155.         self::TYPE_PRINTABLE_STRING     => 'printableString',
  156.         self::TYPE_TELETEX_STRING       => 'teletexString',
  157.         self::TYPE_VIDEOTEX_STRING      => 'videotexString',
  158.         self::TYPE_IA5_STRING           => 'ia5String',
  159.         self::TYPE_UTC_TIME             => 'utcTime',
  160.         self::TYPE_GENERALIZED_TIME     => 'generalTime',
  161.         self::TYPE_GRAPHIC_STRING       => 'graphicString',
  162.         self::TYPE_VISIBLE_STRING       => 'visibleString',
  163.         self::TYPE_GENERAL_STRING       => 'generalString',
  164.         self::TYPE_UNIVERSAL_STRING     => 'universalString',
  165.         //self::TYPE_CHARACTER_STRING     => 'characterString',
  166.         self::TYPE_BMP_STRING           => 'bmpString'
  167.     ];
  168.  
  169.     /**
  170.      * String type to character size mapping table.
  171.      *
  172.      * Non-convertable types are absent from this table.
  173.      * size == 0 indicates variable length encoding.
  174.      *
  175.      * @var array
  176.      */
  177.     const STRING_TYPE_SIZE = [
  178.         self::TYPE_UTF8_STRING      => 0,
  179.         self::TYPE_BMP_STRING       => 2,
  180.         self::TYPE_UNIVERSAL_STRING => 4,
  181.         self::TYPE_PRINTABLE_STRING => 1,
  182.         self::TYPE_TELETEX_STRING   => 1,
  183.         self::TYPE_IA5_STRING       => 1,
  184.         self::TYPE_VISIBLE_STRING   => 1,
  185.     ];
  186.  
  187.     /**
  188.      * Parse BER-encoding
  189.      *
  190.      * Serves a similar purpose to openssl's asn1parse
  191.      *
  192.      * @param Element|string $encoded
  193.      * @return ?array
  194.      */
  195.     public static function decodeBER($encoded)
  196.     {
  197.         if ($encoded instanceof Element) {
  198.             $encoded = $encoded->element;
  199.         }
  200.  
  201.         self::$encoded = $encoded;
  202.  
  203.         $decoded = self::decode_ber($encoded);
  204.         if ($decoded === false) {
  205.             return null;
  206.         }
  207.  
  208.         return [$decoded];
  209.     }
  210.  
  211.     /**
  212.      * Parse BER-encoding (Helper function)
  213.      *
  214.      * Sometimes we want to get the BER encoding of a particular tag.  $start lets us do that without having to reencode.
  215.      * $encoded is passed by reference for the recursive calls done for self::TYPE_BIT_STRING and
  216.      * self::TYPE_OCTET_STRING. In those cases, the indefinite length is used.
  217.      *
  218.      * @param string $encoded
  219.      * @param int $start
  220.      * @param int $encoded_pos
  221.      * @return array|bool
  222.      */
  223.     private static function decode_ber($encoded, $start = 0, $encoded_pos = 0)
  224.     {
  225.         $current = ['start' => $start];
  226.  
  227.         if (!isset($encoded[$encoded_pos])) {
  228.             return false;
  229.         }
  230.         $type = ord($encoded[$encoded_pos++]);
  231.         $startOffset = 1;
  232.  
  233.         $constructed = ($type >> 5) & 1;
  234.  
  235.         $tag = $type & 0x1F;
  236.         if ($tag == 0x1F) {
  237.             $tag = 0;
  238.             // process septets (since the eighth bit is ignored, it's not an octet)
  239.             do {
  240.                 if (!isset($encoded[$encoded_pos])) {
  241.                     return false;
  242.                 }
  243.                 $temp = ord($encoded[$encoded_pos++]);
  244.                 $startOffset++;
  245.                 $loop = $temp >> 7;
  246.                 $tag <<= 7;
  247.                 $temp &= 0x7F;
  248.                 // "bits 7 to 1 of the first subsequent octet shall not all be zero"
  249.                 if ($startOffset == 2 && $temp == 0) {
  250.                     return false;
  251.                 }
  252.                 $tag |= $temp;
  253.             } while ($loop);
  254.         }
  255.  
  256.         $start += $startOffset;
  257.  
  258.         // Length, as discussed in paragraph 8.1.3 of X.690-0207.pdf#page=13
  259.         if (!isset($encoded[$encoded_pos])) {
  260.             return false;
  261.         }
  262.         $length = ord($encoded[$encoded_pos++]);
  263.         $start++;
  264.         if ($length == 0x80) { // indefinite length
  265.             // "[A sender shall] use the indefinite form (see 8.1.3.6) if the encoding is constructed and is not all
  266.             //  immediately available." -- paragraph 8.1.3.2.c
  267.             $length = strlen($encoded) - $encoded_pos;
  268.         } elseif ($length & 0x80) { // definite length, long form
  269.             // technically, the long form of the length can be represented by up to 126 octets (bytes), but we'll only
  270.             // support it up to four.
  271.             $length &= 0x7F;
  272.             $temp = substr($encoded, $encoded_pos, $length);
  273.             $encoded_pos += $length;
  274.             // tags of indefinte length don't really have a header length; this length includes the tag
  275.             $current += ['headerlength' => $length + 2];
  276.             $start += $length;
  277.             extract(unpack('Nlength', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)));
  278.             /** @var integer $length */
  279.         } else {
  280.             $current += ['headerlength' => 2];
  281.         }
  282.  
  283.         if ($length > (strlen($encoded) - $encoded_pos)) {
  284.             return false;
  285.         }
  286.  
  287.         $content = substr($encoded, $encoded_pos, $length);
  288.         $content_pos = 0;
  289.  
  290.         // at this point $length can be overwritten. it's only accurate for definite length things as is
  291.  
  292.         /* Class is UNIVERSAL, APPLICATION, PRIVATE, or CONTEXT-SPECIFIC. The UNIVERSAL class is restricted to the ASN.1
  293.            built-in types. It defines an application-independent data type that must be distinguishable from all other
  294.            data types. The other three classes are user defined. The APPLICATION class distinguishes data types that
  295.            have a wide, scattered use within a particular presentation context. PRIVATE distinguishes data types within
  296.            a particular organization or country. CONTEXT-SPECIFIC distinguishes members of a sequence or set, the
  297.            alternatives of a CHOICE, or universally tagged set members. Only the class number appears in braces for this
  298.            data type; the term CONTEXT-SPECIFIC does not appear.
  299.  
  300.              -- http://www.obj-sys.com/asn1tutorial/node12.html */
  301.         $class = ($type >> 6) & 3;
  302.         switch ($class) {
  303.             case self::CLASS_APPLICATION:
  304.             case self::CLASS_PRIVATE:
  305.             case self::CLASS_CONTEXT_SPECIFIC:
  306.                 if (!$constructed) {
  307.                     return [
  308.                         'type'     => $class,
  309.                         'constant' => $tag,
  310.                         'content'  => $content,
  311.                         'length'   => $length + $start - $current['start']
  312.                     ] + $current;
  313.                 }
  314.  
  315.                 $newcontent = [];
  316.                 $remainingLength = $length;
  317.                 while ($remainingLength > 0) {
  318.                     $temp = self::decode_ber($content, $start, $content_pos);
  319.                     if ($temp === false) {
  320.                         break;
  321.                     }
  322.                     $length = $temp['length'];
  323.                     // end-of-content octets - see paragraph 8.1.5
  324.                     if (substr($content, $content_pos + $length, 2) == "\0\0") {
  325.                         $length += 2;
  326.                         $start += $length;
  327.                         $newcontent[] = $temp;
  328.                         break;
  329.                     }
  330.                     $start += $length;
  331.                     $remainingLength -= $length;
  332.                     $newcontent[] = $temp;
  333.                     $content_pos += $length;
  334.                 }
  335.  
  336.                 return [
  337.                     'type'     => $class,
  338.                     'constant' => $tag,
  339.                     // the array encapsulation is for BC with the old format
  340.                     'content'  => $newcontent,
  341.                     // the only time when $content['headerlength'] isn't defined is when the length is indefinite.
  342.                     // the absence of $content['headerlength'] is how we know if something is indefinite or not.
  343.                     // technically, it could be defined to be 2 and then another indicator could be used but whatever.
  344.                     'length'   => $start - $current['start']
  345.                 ] + $current;
  346.         }
  347.  
  348.         $current += ['type' => $tag];
  349.  
  350.         // decode UNIVERSAL tags
  351.         switch ($tag) {
  352.             case self::TYPE_BOOLEAN:
  353.                 // "The contents octets shall consist of a single octet." -- paragraph 8.2.1
  354.                 if ($constructed || strlen($content) != 1) {
  355.                     return false;
  356.                 }
  357.                 $current['content'] = (bool) ord($content[$content_pos]);
  358.                 break;
  359.             case self::TYPE_INTEGER:
  360.             case self::TYPE_ENUMERATED:
  361.                 if ($constructed) {
  362.                     return false;
  363.                 }
  364.                 $current['content'] = new BigInteger(substr($content, $content_pos), -256);
  365.                 break;
  366.             case self::TYPE_REAL: // not currently supported
  367.                 return false;
  368.             case self::TYPE_BIT_STRING:
  369.                 // The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit,
  370.                 // the number of unused bits in the final subsequent octet. The number shall be in the range zero to
  371.                 // seven.
  372.                 if (!$constructed) {
  373.                     $current['content'] = substr($content, $content_pos);
  374.                 } else {
  375.                     $temp = self::decode_ber($content, $start, $content_pos);
  376.                     if ($temp === false) {
  377.                         return false;
  378.                     }
  379.                     $length -= (strlen($content) - $content_pos);
  380.                     $last = count($temp) - 1;
  381.                     for ($i = 0; $i < $last; $i++) {
  382.                         // all subtags should be bit strings
  383.                         if ($temp[$i]['type'] != self::TYPE_BIT_STRING) {
  384.                             return false;
  385.                         }
  386.                         $current['content'] .= substr($temp[$i]['content'], 1);
  387.                     }
  388.                     // all subtags should be bit strings
  389.                     if ($temp[$last]['type'] != self::TYPE_BIT_STRING) {
  390.                         return false;
  391.                     }
  392.                     $current['content'] = $temp[$last]['content'][0] . $current['content'] . substr($temp[$i]['content'], 1);
  393.                 }
  394.                 break;
  395.             case self::TYPE_OCTET_STRING:
  396.                 if (!$constructed) {
  397.                     $current['content'] = substr($content, $content_pos);
  398.                 } else {
  399.                     $current['content'] = '';
  400.                     $length = 0;
  401.                     while (substr($content, $content_pos, 2) != "\0\0") {
  402.                         $temp = self::decode_ber($content, $length + $start, $content_pos);
  403.                         if ($temp === false) {
  404.                             return false;
  405.                         }
  406.                         $content_pos += $temp['length'];
  407.                         // all subtags should be octet strings
  408.                         if ($temp['type'] != self::TYPE_OCTET_STRING) {
  409.                             return false;
  410.                         }
  411.                         $current['content'] .= $temp['content'];
  412.                         $length += $temp['length'];
  413.                     }
  414.                     if (substr($content, $content_pos, 2) == "\0\0") {
  415.                         $length += 2; // +2 for the EOC
  416.                     }
  417.                 }
  418.                 break;
  419.             case self::TYPE_NULL:
  420.                 // "The contents octets shall not contain any octets." -- paragraph 8.8.2
  421.                 if ($constructed || strlen($content)) {
  422.                     return false;
  423.                 }
  424.                 break;
  425.             case self::TYPE_SEQUENCE:
  426.             case self::TYPE_SET:
  427.                 if (!$constructed) {
  428.                     return false;
  429.                 }
  430.                 $offset = 0;
  431.                 $current['content'] = [];
  432.                 $content_len = strlen($content);
  433.                 while ($content_pos < $content_len) {
  434.                     // if indefinite length construction was used and we have an end-of-content string next
  435.                     // see paragraphs 8.1.1.3, 8.1.3.2, 8.1.3.6, 8.1.5, and (for an example) 8.6.4.2
  436.                     if (!isset($current['headerlength']) && substr($content, $content_pos, 2) == "\0\0") {
  437.                         $length = $offset + 2; // +2 for the EOC
  438.                         break 2;
  439.                     }
  440.                     $temp = self::decode_ber($content, $start + $offset, $content_pos);
  441.                     if ($temp === false) {
  442.                         return false;
  443.                     }
  444.                     $content_pos += $temp['length'];
  445.                     $current['content'][] = $temp;
  446.                     $offset += $temp['length'];
  447.                 }
  448.                 break;
  449.             case self::TYPE_OBJECT_IDENTIFIER:
  450.                 if ($constructed) {
  451.                     return false;
  452.                 }
  453.                 $current['content'] = self::decodeOID(substr($content, $content_pos));
  454.                 if ($current['content'] === false) {
  455.                     return false;
  456.                 }
  457.                 break;
  458.             /* Each character string type shall be encoded as if it had been declared:
  459.                [UNIVERSAL x] IMPLICIT OCTET STRING
  460.  
  461.                  -- X.690-0207.pdf#page=23 (paragraph 8.21.3)
  462.  
  463.                Per that, we're not going to do any validation.  If there are any illegal characters in the string,
  464.                we don't really care */
  465.             case self::TYPE_NUMERIC_STRING:
  466.                 // 0,1,2,3,4,5,6,7,8,9, and space
  467.             case self::TYPE_PRINTABLE_STRING:
  468.                 // Upper and lower case letters, digits, space, apostrophe, left/right parenthesis, plus sign, comma,
  469.                 // hyphen, full stop, solidus, colon, equal sign, question mark
  470.             case self::TYPE_TELETEX_STRING:
  471.                 // The Teletex character set in CCITT's T61, space, and delete
  472.                 // see http://en.wikipedia.org/wiki/Teletex#Character_sets
  473.             case self::TYPE_VIDEOTEX_STRING:
  474.                 // The Videotex character set in CCITT's T.100 and T.101, space, and delete
  475.             case self::TYPE_VISIBLE_STRING:
  476.                 // Printing character sets of international ASCII, and space
  477.             case self::TYPE_IA5_STRING:
  478.                 // International Alphabet 5 (International ASCII)
  479.             case self::TYPE_GRAPHIC_STRING:
  480.                 // All registered G sets, and space
  481.             case self::TYPE_GENERAL_STRING:
  482.                 // All registered C and G sets, space and delete
  483.             case self::TYPE_UTF8_STRING:
  484.                 // ????
  485.             case self::TYPE_BMP_STRING:
  486.                 if ($constructed) {
  487.                     return false;
  488.                 }
  489.                 $current['content'] = substr($content, $content_pos);
  490.                 break;
  491.             case self::TYPE_UTC_TIME:
  492.             case self::TYPE_GENERALIZED_TIME:
  493.                 if ($constructed) {
  494.                     return false;
  495.                 }
  496.                 $current['content'] = self::decodeTime(substr($content, $content_pos), $tag);
  497.                 break;
  498.             default:
  499.                 return false;
  500.         }
  501.  
  502.         $start += $length;
  503.  
  504.         // ie. length is the length of the full TLV encoding - it's not just the length of the value
  505.         return $current + ['length' => $start - $current['start']];
  506.     }
  507.  
  508.     /**
  509.      * ASN.1 Map
  510.      *
  511.      * Provides an ASN.1 semantic mapping ($mapping) from a parsed BER-encoding to a human readable format.
  512.      *
  513.      * "Special" mappings may be applied on a per tag-name basis via $special.
  514.      *
  515.      * @param array $decoded
  516.      * @param array $mapping
  517.      * @param array $special
  518.      * @return array|bool|Element|string|null
  519.      */
  520.     public static function asn1map(array $decoded, $mapping, $special = [])
  521.     {
  522.         if (isset($mapping['explicit']) && is_array($decoded['content'])) {
  523.             $decoded = $decoded['content'][0];
  524.         }
  525.  
  526.         switch (true) {
  527.             case $mapping['type'] == self::TYPE_ANY:
  528.                 $intype = $decoded['type'];
  529.                 // !isset(self::ANY_MAP[$intype]) produces a fatal error on PHP 5.6
  530.                 if (isset($decoded['constant']) || !array_key_exists($intype, self::ANY_MAP) || (ord(self::$encoded[$decoded['start']]) & 0x20)) {
  531.                     return new Element(substr(self::$encoded, $decoded['start'], $decoded['length']));
  532.                 }
  533.                 $inmap = self::ANY_MAP[$intype];
  534.                 if (is_string($inmap)) {
  535.                     return [$inmap => self::asn1map($decoded, ['type' => $intype] + $mapping, $special)];
  536.                 }
  537.                 break;
  538.             case $mapping['type'] == self::TYPE_CHOICE:
  539.                 foreach ($mapping['children'] as $key => $option) {
  540.                     switch (true) {
  541.                         case isset($option['constant']) && $option['constant'] == $decoded['constant']:
  542.                         case !isset($option['constant']) && $option['type'] == $decoded['type']:
  543.                             $value = self::asn1map($decoded, $option, $special);
  544.                             break;
  545.                         case !isset($option['constant']) && $option['type'] == self::TYPE_CHOICE:
  546.                             $v = self::asn1map($decoded, $option, $special);
  547.                             if (isset($v)) {
  548.                                 $value = $v;
  549.                             }
  550.                     }
  551.                     if (isset($value)) {
  552.                         if (isset($special[$key])) {
  553.                             $value = $special[$key]($value);
  554.                         }
  555.                         return [$key => $value];
  556.                     }
  557.                 }
  558.                 return null;
  559.             case isset($mapping['implicit']):
  560.             case isset($mapping['explicit']):
  561.             case $decoded['type'] == $mapping['type']:
  562.                 break;
  563.             default:
  564.                 // if $decoded['type'] and $mapping['type'] are both strings, but different types of strings,
  565.                 // let it through
  566.                 switch (true) {
  567.                     case $decoded['type'] < 18: // self::TYPE_NUMERIC_STRING == 18
  568.                     case $decoded['type'] > 30: // self::TYPE_BMP_STRING == 30
  569.                     case $mapping['type'] < 18:
  570.                     case $mapping['type'] > 30:
  571.                         return null;
  572.                 }
  573.         }
  574.  
  575.         if (isset($mapping['implicit'])) {
  576.             $decoded['type'] = $mapping['type'];
  577.         }
  578.  
  579.         switch ($decoded['type']) {
  580.             case self::TYPE_SEQUENCE:
  581.                 $map = [];
  582.  
  583.                 // ignore the min and max
  584.                 if (isset($mapping['min']) && isset($mapping['max'])) {
  585.                     $child = $mapping['children'];
  586.                     foreach ($decoded['content'] as $content) {
  587.                         if (($map[] = self::asn1map($content, $child, $special)) === null) {
  588.                             return null;
  589.                         }
  590.                     }
  591.  
  592.                     return $map;
  593.                 }
  594.  
  595.                 $n = count($decoded['content']);
  596.                 $i = 0;
  597.  
  598.                 foreach ($mapping['children'] as $key => $child) {
  599.                     $maymatch = $i < $n; // Match only existing input.
  600.                     if ($maymatch) {
  601.                         $temp = $decoded['content'][$i];
  602.  
  603.                         if ($child['type'] != self::TYPE_CHOICE) {
  604.                             // Get the mapping and input class & constant.
  605.                             $childClass = $tempClass = self::CLASS_UNIVERSAL;
  606.                             $constant = null;
  607.                             if (isset($temp['constant'])) {
  608.                                 $tempClass = $temp['type'];
  609.                             }
  610.                             if (isset($child['class'])) {
  611.                                 $childClass = $child['class'];
  612.                                 $constant = $child['cast'];
  613.                             } elseif (isset($child['constant'])) {
  614.                                 $childClass = self::CLASS_CONTEXT_SPECIFIC;
  615.                                 $constant = $child['constant'];
  616.                             }
  617.  
  618.                             if (isset($constant) && isset($temp['constant'])) {
  619.                                 // Can only match if constants and class match.
  620.                                 $maymatch = $constant == $temp['constant'] && $childClass == $tempClass;
  621.                             } else {
  622.                                 // Can only match if no constant expected and type matches or is generic.
  623.                                 $maymatch = !isset($child['constant']) && array_search($child['type'], [$temp['type'], self::TYPE_ANY, self::TYPE_CHOICE]) !== false;
  624.                             }
  625.                         }
  626.                     }
  627.  
  628.                     if ($maymatch) {
  629.                         // Attempt submapping.
  630.                         $candidate = self::asn1map($temp, $child, $special);
  631.                         $maymatch = $candidate !== null;
  632.                     }
  633.  
  634.                     if ($maymatch) {
  635.                         // Got the match: use it.
  636.                         if (isset($special[$key])) {
  637.                             $candidate = $special[$key]($candidate);
  638.                         }
  639.                         $map[$key] = $candidate;
  640.                         $i++;
  641.                     } elseif (isset($child['default'])) {
  642.                         $map[$key] = $child['default'];
  643.                     } elseif (!isset($child['optional'])) {
  644.                         return null; // Syntax error.
  645.                     }
  646.                 }
  647.  
  648.                 // Fail mapping if all input items have not been consumed.
  649.                 return $i < $n ? null : $map;
  650.  
  651.             // the main diff between sets and sequences is the encapsulation of the foreach in another for loop
  652.             case self::TYPE_SET:
  653.                 $map = [];
  654.  
  655.                 // ignore the min and max
  656.                 if (isset($mapping['min']) && isset($mapping['max'])) {
  657.                     $child = $mapping['children'];
  658.                     foreach ($decoded['content'] as $content) {
  659.                         if (($map[] = self::asn1map($content, $child, $special)) === null) {
  660.                             return null;
  661.                         }
  662.                     }
  663.  
  664.                     return $map;
  665.                 }
  666.  
  667.                 for ($i = 0; $i < count($decoded['content']); $i++) {
  668.                     $temp = $decoded['content'][$i];
  669.                     $tempClass = self::CLASS_UNIVERSAL;
  670.                     if (isset($temp['constant'])) {
  671.                         $tempClass = $temp['type'];
  672.                     }
  673.  
  674.                     foreach ($mapping['children'] as $key => $child) {
  675.                         if (isset($map[$key])) {
  676.                             continue;
  677.                         }
  678.                         $maymatch = true;
  679.                         if ($child['type'] != self::TYPE_CHOICE) {
  680.                             $childClass = self::CLASS_UNIVERSAL;
  681.                             $constant = null;
  682.                             if (isset($child['class'])) {
  683.                                 $childClass = $child['class'];
  684.                                 $constant = $child['cast'];
  685.                             } elseif (isset($child['constant'])) {
  686.                                 $childClass = self::CLASS_CONTEXT_SPECIFIC;
  687.                                 $constant = $child['constant'];
  688.                             }
  689.  
  690.                             if (isset($constant) && isset($temp['constant'])) {
  691.                                 // Can only match if constants and class match.
  692.                                 $maymatch = $constant == $temp['constant'] && $childClass == $tempClass;
  693.                             } else {
  694.                                 // Can only match if no constant expected and type matches or is generic.
  695.                                 $maymatch = !isset($child['constant']) && array_search($child['type'], [$temp['type'], self::TYPE_ANY, self::TYPE_CHOICE]) !== false;
  696.                             }
  697.                         }
  698.  
  699.                         if ($maymatch) {
  700.                             // Attempt submapping.
  701.                             $candidate = self::asn1map($temp, $child, $special);
  702.                             $maymatch = $candidate !== null;
  703.                         }
  704.  
  705.                         if (!$maymatch) {
  706.                             break;
  707.                         }
  708.  
  709.                         // Got the match: use it.
  710.                         if (isset($special[$key])) {
  711.                             $candidate = $special[$key]($candidate);
  712.                         }
  713.                         $map[$key] = $candidate;
  714.                         break;
  715.                     }
  716.                 }
  717.  
  718.                 foreach ($mapping['children'] as $key => $child) {
  719.                     if (!isset($map[$key])) {
  720.                         if (isset($child['default'])) {
  721.                             $map[$key] = $child['default'];
  722.                         } elseif (!isset($child['optional'])) {
  723.                             return null;
  724.                         }
  725.                     }
  726.                 }
  727.                 return $map;
  728.             case self::TYPE_OBJECT_IDENTIFIER:
  729.                 return isset(self::$oids[$decoded['content']]) ? self::$oids[$decoded['content']] : $decoded['content'];
  730.             case self::TYPE_UTC_TIME:
  731.             case self::TYPE_GENERALIZED_TIME:
  732.                 // for explicitly tagged optional stuff
  733.                 if (is_array($decoded['content'])) {
  734.                     $decoded['content'] = $decoded['content'][0]['content'];
  735.                 }
  736.                 // for implicitly tagged optional stuff
  737.                 // in theory, doing isset($mapping['implicit']) would work but malformed certs do exist
  738.                 // in the wild that OpenSSL decodes without issue so we'll support them as well
  739.                 if (!is_object($decoded['content'])) {
  740.                     $decoded['content'] = self::decodeTime($decoded['content'], $decoded['type']);
  741.                 }
  742.                 return $decoded['content'] ? $decoded['content']->format(self::$format) : false;
  743.             case self::TYPE_BIT_STRING:
  744.                 if (isset($mapping['mapping'])) {
  745.                     $offset = ord($decoded['content'][0]);
  746.                     $size = (strlen($decoded['content']) - 1) * 8 - $offset;
  747.                     /*
  748.                        From X.680-0207.pdf#page=46 (21.7):
  749.  
  750.                        "When a "NamedBitList" is used in defining a bitstring type ASN.1 encoding rules are free to add (or remove)
  751.                         arbitrarily any trailing 0 bits to (or from) values that are being encoded or decoded. Application designers should
  752.                         therefore ensure that different semantics are not associated with such values which differ only in the number of trailing
  753.                         0 bits."
  754.                     */
  755.                     $bits = count($mapping['mapping']) == $size ? [] : array_fill(0, count($mapping['mapping']) - $size, false);
  756.                     for ($i = strlen($decoded['content']) - 1; $i > 0; $i--) {
  757.                         $current = ord($decoded['content'][$i]);
  758.                         for ($j = $offset; $j < 8; $j++) {
  759.                             $bits[] = (bool) ($current & (1 << $j));
  760.                         }
  761.                         $offset = 0;
  762.                     }
  763.                     $values = [];
  764.                     $map = array_reverse($mapping['mapping']);
  765.                     foreach ($map as $i => $value) {
  766.                         if ($bits[$i]) {
  767.                             $values[] = $value;
  768.                         }
  769.                     }
  770.                     return $values;
  771.                 }
  772.                 // fall-through
  773.             case self::TYPE_OCTET_STRING:
  774.                 return $decoded['content'];
  775.             case self::TYPE_NULL:
  776.                 return '';
  777.             case self::TYPE_BOOLEAN:
  778.             case self::TYPE_NUMERIC_STRING:
  779.             case self::TYPE_PRINTABLE_STRING:
  780.             case self::TYPE_TELETEX_STRING:
  781.             case self::TYPE_VIDEOTEX_STRING:
  782.             case self::TYPE_IA5_STRING:
  783.             case self::TYPE_GRAPHIC_STRING:
  784.             case self::TYPE_VISIBLE_STRING:
  785.             case self::TYPE_GENERAL_STRING:
  786.             case self::TYPE_UNIVERSAL_STRING:
  787.             case self::TYPE_UTF8_STRING:
  788.             case self::TYPE_BMP_STRING:
  789.                 return $decoded['content'];
  790.             case self::TYPE_INTEGER:
  791.             case self::TYPE_ENUMERATED:
  792.                 $temp = $decoded['content'];
  793.                 if (isset($mapping['implicit'])) {
  794.                     $temp = new BigInteger($decoded['content'], -256);
  795.                 }
  796.                 if (isset($mapping['mapping'])) {
  797.                     $temp = (int) $temp->toString();
  798.                     return isset($mapping['mapping'][$temp]) ?
  799.                         $mapping['mapping'][$temp] :
  800.                         false;
  801.                 }
  802.                 return $temp;
  803.         }
  804.     }
  805.  
  806.     /**
  807.      * DER-decode the length
  808.      *
  809.      * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4.  See
  810.      * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  811.      *
  812.      * @param string $string
  813.      * @return int
  814.      */
  815.     public static function decodeLength(&$string)
  816.     {
  817.         $length = ord(Strings::shift($string));
  818.         if ($length & 0x80) { // definite length, long form
  819.             $length &= 0x7F;
  820.             $temp = Strings::shift($string, $length);
  821.             list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  822.         }
  823.         return $length;
  824.     }
  825.  
  826.     /**
  827.      * ASN.1 Encode
  828.      *
  829.      * DER-encodes an ASN.1 semantic mapping ($mapping).  Some libraries would probably call this function
  830.      * an ASN.1 compiler.
  831.      *
  832.      * "Special" mappings can be applied via $special.
  833.      *
  834.      * @param Element|string|array $source
  835.      * @param array $mapping
  836.      * @param array $special
  837.      * @return string
  838.      */
  839.     public static function encodeDER($source, $mapping, $special = [])
  840.     {
  841.         self::$location = [];
  842.         return self::encode_der($source, $mapping, null, $special);
  843.     }
  844.  
  845.     /**
  846.      * ASN.1 Encode (Helper function)
  847.      *
  848.      * @param Element|string|array|null $source
  849.      * @param array $mapping
  850.      * @param int $idx
  851.      * @param array $special
  852.      * @return string
  853.      */
  854.     private static function encode_der($source, array $mapping, $idx = null, array $special = [])
  855.     {
  856.         if ($source instanceof Element) {
  857.             return $source->element;
  858.         }
  859.  
  860.         // do not encode (implicitly optional) fields with value set to default
  861.         if (isset($mapping['default']) && $source === $mapping['default']) {
  862.             return '';
  863.         }
  864.  
  865.         if (isset($idx)) {
  866.             if (isset($special[$idx])) {
  867.                 $source = $special[$idx]($source);
  868.             }
  869.             self::$location[] = $idx;
  870.         }
  871.  
  872.         $tag = $mapping['type'];
  873.  
  874.         switch ($tag) {
  875.             case self::TYPE_SET:    // Children order is not important, thus process in sequence.
  876.             case self::TYPE_SEQUENCE:
  877.                 $tag |= 0x20; // set the constructed bit
  878.  
  879.                 // ignore the min and max
  880.                 if (isset($mapping['min']) && isset($mapping['max'])) {
  881.                     $value = [];
  882.                     $child = $mapping['children'];
  883.  
  884.                     foreach ($source as $content) {
  885.                         $temp = self::encode_der($content, $child, null, $special);
  886.                         if ($temp === false) {
  887.                             return false;
  888.                         }
  889.                         $value[] = $temp;
  890.                     }
  891.                     /* "The encodings of the component values of a set-of value shall appear in ascending order, the encodings being compared
  892.                         as octet strings with the shorter components being padded at their trailing end with 0-octets.
  893.                         NOTE - The padding octets are for comparison purposes only and do not appear in the encodings."
  894.  
  895.                        -- sec 11.6 of http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf  */
  896.                     if ($mapping['type'] == self::TYPE_SET) {
  897.                         sort($value);
  898.                     }
  899.                     $value = implode('', $value);
  900.                     break;
  901.                 }
  902.  
  903.                 $value = '';
  904.                 foreach ($mapping['children'] as $key => $child) {
  905.                     if (!array_key_exists($key, $source)) {
  906.                         if (!isset($child['optional'])) {
  907.                             return false;
  908.                         }
  909.                         continue;
  910.                     }
  911.  
  912.                     $temp = self::encode_der($source[$key], $child, $key, $special);
  913.                     if ($temp === false) {
  914.                         return false;
  915.                     }
  916.  
  917.                     // An empty child encoding means it has been optimized out.
  918.                     // Else we should have at least one tag byte.
  919.                     if ($temp === '') {
  920.                         continue;
  921.                     }
  922.  
  923.                     // if isset($child['constant']) is true then isset($child['optional']) should be true as well
  924.                     if (isset($child['constant'])) {
  925.                         /*
  926.                            From X.680-0207.pdf#page=58 (30.6):
  927.  
  928.                            "The tagging construction specifies explicit tagging if any of the following holds:
  929.                             ...
  930.                             c) the "Tag Type" alternative is used and the value of "TagDefault" for the module is IMPLICIT TAGS or
  931.                             AUTOMATIC TAGS, but the type defined by "Type" is an untagged choice type, an untagged open type, or
  932.                             an untagged "DummyReference" (see ITU-T Rec. X.683 | ISO/IEC 8824-4, 8.3)."
  933.                          */
  934.                         if (isset($child['explicit']) || $child['type'] == self::TYPE_CHOICE) {
  935.                             $subtag = chr((self::CLASS_CONTEXT_SPECIFIC << 6) | 0x20 | $child['constant']);
  936.                             $temp = $subtag . self::encodeLength(strlen($temp)) . $temp;
  937.                         } else {
  938.                             $subtag = chr((self::CLASS_CONTEXT_SPECIFIC << 6) | (ord($temp[0]) & 0x20) | $child['constant']);
  939.                             $temp = $subtag . substr($temp, 1);
  940.                         }
  941.                     }
  942.                     $value .= $temp;
  943.                 }
  944.                 break;
  945.             case self::TYPE_CHOICE:
  946.                 $temp = false;
  947.  
  948.                 foreach ($mapping['children'] as $key => $child) {
  949.                     if (!isset($source[$key])) {
  950.                         continue;
  951.                     }
  952.  
  953.                     $temp = self::encode_der($source[$key], $child, $key, $special);
  954.                     if ($temp === false) {
  955.                         return false;
  956.                     }
  957.  
  958.                     // An empty child encoding means it has been optimized out.
  959.                     // Else we should have at least one tag byte.
  960.                     if ($temp === '') {
  961.                         continue;
  962.                     }
  963.  
  964.                     $tag = ord($temp[0]);
  965.  
  966.                     // if isset($child['constant']) is true then isset($child['optional']) should be true as well
  967.                     if (isset($child['constant'])) {
  968.                         if (isset($child['explicit']) || $child['type'] == self::TYPE_CHOICE) {
  969.                             $subtag = chr((self::CLASS_CONTEXT_SPECIFIC << 6) | 0x20 | $child['constant']);
  970.                             $temp = $subtag . self::encodeLength(strlen($temp)) . $temp;
  971.                         } else {
  972.                             $subtag = chr((self::CLASS_CONTEXT_SPECIFIC << 6) | (ord($temp[0]) & 0x20) | $child['constant']);
  973.                             $temp = $subtag . substr($temp, 1);
  974.                         }
  975.                     }
  976.                 }
  977.  
  978.                 if (isset($idx)) {
  979.                     array_pop(self::$location);
  980.                 }
  981.  
  982.                 if ($temp && isset($mapping['cast'])) {
  983.                     $temp[0] = chr(($mapping['class'] << 6) | ($tag & 0x20) | $mapping['cast']);
  984.                 }
  985.  
  986.                 return $temp;
  987.             case self::TYPE_INTEGER:
  988.             case self::TYPE_ENUMERATED:
  989.                 if (!isset($mapping['mapping'])) {
  990.                     if (is_numeric($source)) {
  991.                         $source = new BigInteger($source);
  992.                     }
  993.                     $value = $source->toBytes(true);
  994.                 } else {
  995.                     $value = array_search($source, $mapping['mapping']);
  996.                     if ($value === false) {
  997.                         return false;
  998.                     }
  999.                     $value = new BigInteger($value);
  1000.                     $value = $value->toBytes(true);
  1001.                 }
  1002.                 if (!strlen($value)) {
  1003.                     $value = chr(0);
  1004.                 }
  1005.                 break;
  1006.             case self::TYPE_UTC_TIME:
  1007.             case self::TYPE_GENERALIZED_TIME:
  1008.                 $format = $mapping['type'] == self::TYPE_UTC_TIME ? 'y' : 'Y';
  1009.                 $format .= 'mdHis';
  1010.                 // if $source does _not_ include timezone information within it then assume that the timezone is GMT
  1011.                 $date = new \DateTime($source, new \DateTimeZone('GMT'));
  1012.                 // if $source _does_ include timezone information within it then convert the time to GMT
  1013.                 $date->setTimezone(new \DateTimeZone('GMT'));
  1014.                 $value = $date->format($format) . 'Z';
  1015.                 break;
  1016.             case self::TYPE_BIT_STRING:
  1017.                 if (isset($mapping['mapping'])) {
  1018.                     $bits = array_fill(0, count($mapping['mapping']), 0);
  1019.                     $size = 0;
  1020.                     for ($i = 0; $i < count($mapping['mapping']); $i++) {
  1021.                         if (in_array($mapping['mapping'][$i], $source)) {
  1022.                             $bits[$i] = 1;
  1023.                             $size = $i;
  1024.                         }
  1025.                     }
  1026.  
  1027.                     if (isset($mapping['min']) && $mapping['min'] >= 1 && $size < $mapping['min']) {
  1028.                         $size = $mapping['min'] - 1;
  1029.                     }
  1030.  
  1031.                     $offset = 8 - (($size + 1) & 7);
  1032.                     $offset = $offset !== 8 ? $offset : 0;
  1033.  
  1034.                     $value = chr($offset);
  1035.  
  1036.                     for ($i = $size + 1; $i < count($mapping['mapping']); $i++) {
  1037.                         unset($bits[$i]);
  1038.                     }
  1039.  
  1040.                     $bits = implode('', array_pad($bits, $size + $offset + 1, 0));
  1041.                     $bytes = explode(' ', rtrim(chunk_split($bits, 8, ' ')));
  1042.                     foreach ($bytes as $byte) {
  1043.                         $value .= chr(bindec($byte));
  1044.                     }
  1045.  
  1046.                     break;
  1047.                 }
  1048.                 // fall-through
  1049.             case self::TYPE_OCTET_STRING:
  1050.                 /* The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit,
  1051.                    the number of unused bits in the final subsequent octet. The number shall be in the range zero to seven.
  1052.  
  1053.                    -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=16 */
  1054.                 $value = $source;
  1055.                 break;
  1056.             case self::TYPE_OBJECT_IDENTIFIER:
  1057.                 $value = self::encodeOID($source);
  1058.                 break;
  1059.             case self::TYPE_ANY:
  1060.                 $loc = self::$location;
  1061.                 if (isset($idx)) {
  1062.                     array_pop(self::$location);
  1063.                 }
  1064.  
  1065.                 switch (true) {
  1066.                     case !isset($source):
  1067.                         return self::encode_der(null, ['type' => self::TYPE_NULL] + $mapping, null, $special);
  1068.                     case is_int($source):
  1069.                     case $source instanceof BigInteger:
  1070.                         return self::encode_der($source, ['type' => self::TYPE_INTEGER] + $mapping, null, $special);
  1071.                     case is_float($source):
  1072.                         return self::encode_der($source, ['type' => self::TYPE_REAL] + $mapping, null, $special);
  1073.                     case is_bool($source):
  1074.                         return self::encode_der($source, ['type' => self::TYPE_BOOLEAN] + $mapping, null, $special);
  1075.                     case is_array($source) && count($source) == 1:
  1076.                         $typename = implode('', array_keys($source));
  1077.                         $outtype = array_search($typename, self::ANY_MAP, true);
  1078.                         if ($outtype !== false) {
  1079.                             return self::encode_der($source[$typename], ['type' => $outtype] + $mapping, null, $special);
  1080.                         }
  1081.                 }
  1082.  
  1083.                 $filters = self::$filters;
  1084.                 foreach ($loc as $part) {
  1085.                     if (!isset($filters[$part])) {
  1086.                         $filters = false;
  1087.                         break;
  1088.                     }
  1089.                     $filters = $filters[$part];
  1090.                 }
  1091.                 if ($filters === false) {
  1092.                     throw new \RuntimeException('No filters defined for ' . implode('/', $loc));
  1093.                 }
  1094.                 return self::encode_der($source, $filters + $mapping, null, $special);
  1095.             case self::TYPE_NULL:
  1096.                 $value = '';
  1097.                 break;
  1098.             case self::TYPE_NUMERIC_STRING:
  1099.             case self::TYPE_TELETEX_STRING:
  1100.             case self::TYPE_PRINTABLE_STRING:
  1101.             case self::TYPE_UNIVERSAL_STRING:
  1102.             case self::TYPE_UTF8_STRING:
  1103.             case self::TYPE_BMP_STRING:
  1104.             case self::TYPE_IA5_STRING:
  1105.             case self::TYPE_VISIBLE_STRING:
  1106.             case self::TYPE_VIDEOTEX_STRING:
  1107.             case self::TYPE_GRAPHIC_STRING:
  1108.             case self::TYPE_GENERAL_STRING:
  1109.                 $value = $source;
  1110.                 break;
  1111.             case self::TYPE_BOOLEAN:
  1112.                 $value = $source ? "\xFF" : "\x00";
  1113.                 break;
  1114.             default:
  1115.                 throw new \RuntimeException('Mapping provides no type definition for ' . implode('/', self::$location));
  1116.         }
  1117.  
  1118.         if (isset($idx)) {
  1119.             array_pop(self::$location);
  1120.         }
  1121.  
  1122.         if (isset($mapping['cast'])) {
  1123.             if (isset($mapping['explicit']) || $mapping['type'] == self::TYPE_CHOICE) {
  1124.                 $value = chr($tag) . self::encodeLength(strlen($value)) . $value;
  1125.                 $tag = ($mapping['class'] << 6) | 0x20 | $mapping['cast'];
  1126.             } else {
  1127.                 $tag = ($mapping['class'] << 6) | (ord($temp[0]) & 0x20) | $mapping['cast'];
  1128.             }
  1129.         }
  1130.  
  1131.         return chr($tag) . self::encodeLength(strlen($value)) . $value;
  1132.     }
  1133.  
  1134.     /**
  1135.      * BER-decode the OID
  1136.      *
  1137.      * Called by _decode_ber()
  1138.      *
  1139.      * @param string $content
  1140.      * @return string
  1141.      */
  1142.     public static function decodeOID($content)
  1143.     {
  1144.         static $eighty;
  1145.         if (!$eighty) {
  1146.             $eighty = new BigInteger(80);
  1147.         }
  1148.  
  1149.         $oid = [];
  1150.         $pos = 0;
  1151.         $len = strlen($content);
  1152.  
  1153.         if (ord($content[$len - 1]) & 0x80) {
  1154.             return false;
  1155.         }
  1156.  
  1157.         $n = new BigInteger();
  1158.         while ($pos < $len) {
  1159.             $temp = ord($content[$pos++]);
  1160.             $n = $n->bitwise_leftShift(7);
  1161.             $n = $n->bitwise_or(new BigInteger($temp & 0x7F));
  1162.             if (~$temp & 0x80) {
  1163.                 $oid[] = $n;
  1164.                 $n = new BigInteger();
  1165.             }
  1166.         }
  1167.         $part1 = array_shift($oid);
  1168.         $first = floor(ord($content[0]) / 40);
  1169.         /*
  1170.           "This packing of the first two object identifier components recognizes that only three values are allocated from the root
  1171.            node, and at most 39 subsequent values from nodes reached by X = 0 and X = 1."
  1172.  
  1173.           -- https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=22
  1174.         */
  1175.         if ($first <= 2) { // ie. 0 <= ord($content[0]) < 120 (0x78)
  1176.             array_unshift($oid, ord($content[0]) % 40);
  1177.             array_unshift($oid, $first);
  1178.         } else {
  1179.             array_unshift($oid, $part1->subtract($eighty));
  1180.             array_unshift($oid, 2);
  1181.         }
  1182.  
  1183.         return implode('.', $oid);
  1184.     }
  1185.  
  1186.     /**
  1187.      * DER-encode the OID
  1188.      *
  1189.      * Called by _encode_der()
  1190.      *
  1191.      * @param string $source
  1192.      * @return string
  1193.      */
  1194.     public static function encodeOID($source)
  1195.     {
  1196.         static $mask, $zero, $forty;
  1197.         if (!$mask) {
  1198.             $mask = new BigInteger(0x7F);
  1199.             $zero = new BigInteger();
  1200.             $forty = new BigInteger(40);
  1201.         }
  1202.  
  1203.         if (!preg_match('#(?:\d+\.)+#', $source)) {
  1204.             $oid = isset(self::$reverseOIDs[$source]) ? self::$reverseOIDs[$source] : false;
  1205.         } else {
  1206.             $oid = $source;
  1207.         }
  1208.         if ($oid === false) {
  1209.             throw new \RuntimeException('Invalid OID');
  1210.         }
  1211.  
  1212.         $parts = explode('.', $oid);
  1213.         $part1 = array_shift($parts);
  1214.         $part2 = array_shift($parts);
  1215.  
  1216.         $first = new BigInteger($part1);
  1217.         $first = $first->multiply($forty);
  1218.         $first = $first->add(new BigInteger($part2));
  1219.  
  1220.         array_unshift($parts, $first->toString());
  1221.  
  1222.         $value = '';
  1223.         foreach ($parts as $part) {
  1224.             if (!$part) {
  1225.                 $temp = "\0";
  1226.             } else {
  1227.                 $temp = '';
  1228.                 $part = new BigInteger($part);
  1229.                 while (!$part->equals($zero)) {
  1230.                     $submask = $part->bitwise_and($mask);
  1231.                     $submask->setPrecision(8);
  1232.                     $temp = (chr(0x80) | $submask->toBytes()) . $temp;
  1233.                     $part = $part->bitwise_rightShift(7);
  1234.                 }
  1235.                 $temp[strlen($temp) - 1] = $temp[strlen($temp) - 1] & chr(0x7F);
  1236.             }
  1237.             $value .= $temp;
  1238.         }
  1239.  
  1240.         return $value;
  1241.     }
  1242.  
  1243.     /**
  1244.      * BER-decode the time
  1245.      *
  1246.      * Called by _decode_ber() and in the case of implicit tags asn1map().
  1247.      *
  1248.      * @param string $content
  1249.      * @param int $tag
  1250.      * @return \DateTime|false
  1251.      */
  1252.     private static function decodeTime($content, $tag)
  1253.     {
  1254.         /* UTCTime:
  1255.            http://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
  1256.            http://www.obj-sys.com/asn1tutorial/node15.html
  1257.  
  1258.            GeneralizedTime:
  1259.            http://tools.ietf.org/html/rfc5280#section-4.1.2.5.2
  1260.            http://www.obj-sys.com/asn1tutorial/node14.html */
  1261.  
  1262.         $format = 'YmdHis';
  1263.  
  1264.         if ($tag == self::TYPE_UTC_TIME) {
  1265.             // https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=28 says "the seconds
  1266.             // element shall always be present" but none-the-less I've seen X509 certs where it isn't and if the
  1267.             // browsers parse it phpseclib ought to too
  1268.             if (preg_match('#^(\d{10})(Z|[+-]\d{4})$#', $content, $matches)) {
  1269.                 $content = $matches[1] . '00' . $matches[2];
  1270.             }
  1271.             $prefix = substr($content, 0, 2) >= 50 ? '19' : '20';
  1272.             $content = $prefix . $content;
  1273.         } elseif (strpos($content, '.') !== false) {
  1274.             $format .= '.u';
  1275.         }
  1276.  
  1277.         if ($content[strlen($content) - 1] == 'Z') {
  1278.             $content = substr($content, 0, -1) . '+0000';
  1279.         }
  1280.  
  1281.         if (strpos($content, '-') !== false || strpos($content, '+') !== false) {
  1282.             $format .= 'O';
  1283.         }
  1284.  
  1285.         // error supression isn't necessary as of PHP 7.0:
  1286.         // http://php.net/manual/en/migration70.other-changes.php
  1287.         return @\DateTime::createFromFormat($format, $content);
  1288.     }
  1289.  
  1290.     /**
  1291.      * Set the time format
  1292.      *
  1293.      * Sets the time / date format for asn1map().
  1294.      *
  1295.      * @param string $format
  1296.      */
  1297.     public static function setTimeFormat($format)
  1298.     {
  1299.         self::$format = $format;
  1300.     }
  1301.  
  1302.     /**
  1303.      * Load OIDs
  1304.      *
  1305.      * Load the relevant OIDs for a particular ASN.1 semantic mapping.
  1306.      * Previously loaded OIDs are retained.
  1307.      *
  1308.      * @param array $oids
  1309.      */
  1310.     public static function loadOIDs(array $oids)
  1311.     {
  1312.         self::$reverseOIDs += $oids;
  1313.         self::$oids = array_flip(self::$reverseOIDs);
  1314.     }
  1315.  
  1316.     /**
  1317.      * Set filters
  1318.      *
  1319.      * See \phpseclib3\File\X509, etc, for an example.
  1320.      * Previously loaded filters are not retained.
  1321.      *
  1322.      * @param array $filters
  1323.      */
  1324.     public static function setFilters(array $filters)
  1325.     {
  1326.         self::$filters = $filters;
  1327.     }
  1328.  
  1329.     /**
  1330.      * String type conversion
  1331.      *
  1332.      * This is a lazy conversion, dealing only with character size.
  1333.      * No real conversion table is used.
  1334.      *
  1335.      * @param string $in
  1336.      * @param int $from
  1337.      * @param int $to
  1338.      * @return string
  1339.      */
  1340.     public static function convert($in, $from = self::TYPE_UTF8_STRING, $to = self::TYPE_UTF8_STRING)
  1341.     {
  1342.         // isset(self::STRING_TYPE_SIZE[$from] returns a fatal error on PHP 5.6
  1343.         if (!array_key_exists($from, self::STRING_TYPE_SIZE) || !array_key_exists($to, self::STRING_TYPE_SIZE)) {
  1344.             return false;
  1345.         }
  1346.         $insize = self::STRING_TYPE_SIZE[$from];
  1347.         $outsize = self::STRING_TYPE_SIZE[$to];
  1348.         $inlength = strlen($in);
  1349.         $out = '';
  1350.  
  1351.         for ($i = 0; $i < $inlength;) {
  1352.             if ($inlength - $i < $insize) {
  1353.                 return false;
  1354.             }
  1355.  
  1356.             // Get an input character as a 32-bit value.
  1357.             $c = ord($in[$i++]);
  1358.             switch (true) {
  1359.                 case $insize == 4:
  1360.                     $c = ($c << 8) | ord($in[$i++]);
  1361.                     $c = ($c << 8) | ord($in[$i++]);
  1362.                     // fall-through
  1363.                 case $insize == 2:
  1364.                     $c = ($c << 8) | ord($in[$i++]);
  1365.                     // fall-through
  1366.                 case $insize == 1:
  1367.                     break;
  1368.                 case ($c & 0x80) == 0x00:
  1369.                     break;
  1370.                 case ($c & 0x40) == 0x00:
  1371.                     return false;
  1372.                 default:
  1373.                     $bit = 6;
  1374.                     do {
  1375.                         if ($bit > 25 || $i >= $inlength || (ord($in[$i]) & 0xC0) != 0x80) {
  1376.                             return false;
  1377.                         }
  1378.                         $c = ($c << 6) | (ord($in[$i++]) & 0x3F);
  1379.                         $bit += 5;
  1380.                         $mask = 1 << $bit;
  1381.                     } while ($c & $bit);
  1382.                     $c &= $mask - 1;
  1383.                     break;
  1384.             }
  1385.  
  1386.             // Convert and append the character to output string.
  1387.             $v = '';
  1388.             switch (true) {
  1389.                 case $outsize == 4:
  1390.                     $v .= chr($c & 0xFF);
  1391.                     $c >>= 8;
  1392.                     $v .= chr($c & 0xFF);
  1393.                     $c >>= 8;
  1394.                     // fall-through
  1395.                 case $outsize == 2:
  1396.                     $v .= chr($c & 0xFF);
  1397.                     $c >>= 8;
  1398.                     // fall-through
  1399.                 case $outsize == 1:
  1400.                     $v .= chr($c & 0xFF);
  1401.                     $c >>= 8;
  1402.                     if ($c) {
  1403.                         return false;
  1404.                     }
  1405.                     break;
  1406.                 case ($c & 0x80000000) != 0:
  1407.                     return false;
  1408.                 case $c >= 0x04000000:
  1409.                     $v .= chr(0x80 | ($c & 0x3F));
  1410.                     $c = ($c >> 6) | 0x04000000;
  1411.                     // fall-through
  1412.                 case $c >= 0x00200000:
  1413.                     $v .= chr(0x80 | ($c & 0x3F));
  1414.                     $c = ($c >> 6) | 0x00200000;
  1415.                     // fall-through
  1416.                 case $c >= 0x00010000:
  1417.                     $v .= chr(0x80 | ($c & 0x3F));
  1418.                     $c = ($c >> 6) | 0x00010000;
  1419.                     // fall-through
  1420.                 case $c >= 0x00000800:
  1421.                     $v .= chr(0x80 | ($c & 0x3F));
  1422.                     $c = ($c >> 6) | 0x00000800;
  1423.                     // fall-through
  1424.                 case $c >= 0x00000080:
  1425.                     $v .= chr(0x80 | ($c & 0x3F));
  1426.                     $c = ($c >> 6) | 0x000000C0;
  1427.                     // fall-through
  1428.                 default:
  1429.                     $v .= chr($c);
  1430.                     break;
  1431.             }
  1432.             $out .= strrev($v);
  1433.         }
  1434.         return $out;
  1435.     }
  1436.  
  1437.     /**
  1438.      * Extract raw BER from Base64 encoding
  1439.      *
  1440.      * @param string $str
  1441.      * @return string
  1442.      */
  1443.     public static function extractBER($str)
  1444.     {
  1445.         /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them
  1446.          * above and beyond the ceritificate.
  1447.          * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line:
  1448.          *
  1449.          * Bag Attributes
  1450.          *     localKeyID: 01 00 00 00
  1451.          * subject=/O=organization/OU=org unit/CN=common name
  1452.          * issuer=/O=organization/CN=common name
  1453.          */
  1454.         if (strlen($str) > ini_get('pcre.backtrack_limit')) {
  1455.             $temp = $str;
  1456.         } else {
  1457.             $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1);
  1458.             $temp = preg_replace('#-+END.*[\r\n ]*.*#ms', '', $temp, 1);
  1459.         }
  1460.         // remove new lines
  1461.         $temp = str_replace(["\r", "\n", ' '], '', $temp);
  1462.         // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff
  1463.         $temp = preg_replace('#^-+[^-]+-+|-+[^-]+-+$#', '', $temp);
  1464.         $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? Strings::base64_decode($temp) : false;
  1465.         return $temp != false ? $temp : $str;
  1466.     }
  1467.  
  1468.     /**
  1469.      * DER-encode the length
  1470.      *
  1471.      * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4.  See
  1472.      * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1473.      *
  1474.      * @param int $length
  1475.      * @return string
  1476.      */
  1477.     public static function encodeLength($length)
  1478.     {
  1479.         if ($length <= 0x7F) {
  1480.             return chr($length);
  1481.         }
  1482.  
  1483.         $temp = ltrim(pack('N', $length), chr(0));
  1484.         return pack('Ca*', 0x80 | strlen($temp), $temp);
  1485.     }
  1486.  
  1487.     /**
  1488.      * Returns the OID corresponding to a name
  1489.      *
  1490.      * What's returned in the associative array returned by loadX509() (or load*()) is either a name or an OID if
  1491.      * no OID to name mapping is available. The problem with this is that what may be an unmapped OID in one version
  1492.      * of phpseclib may not be unmapped in the next version, so apps that are looking at this OID may not be able
  1493.      * to work from version to version.
  1494.      *
  1495.      * This method will return the OID if a name is passed to it and if no mapping is avialable it'll assume that
  1496.      * what's being passed to it already is an OID and return that instead. A few examples.
  1497.      *
  1498.      * getOID('2.16.840.1.101.3.4.2.1') == '2.16.840.1.101.3.4.2.1'
  1499.      * getOID('id-sha256') == '2.16.840.1.101.3.4.2.1'
  1500.      * getOID('zzz') == 'zzz'
  1501.      *
  1502.      * @param string $name
  1503.      * @return string
  1504.      */
  1505.     public static function getOID($name)
  1506.     {
  1507.         return isset(self::$reverseOIDs[$name]) ? self::$reverseOIDs[$name] : $name;
  1508.     }
  1509. }
  1510.