PageRenderTime 54ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/src/PHPSecLib/File/ASN1.php

https://github.com/dsawardekar/worker
PHP | 1300 lines | 797 code | 113 blank | 390 comment | 174 complexity | e1c4cf445a8251da3c1289524a101654 MD5 | raw file
Possible License(s): Apache-2.0
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Pure-PHP ASN.1 Parser
  5. * PHP versions 4 and 5
  6. * ASN.1 provides the semantics for data encoded using various schemes. The most commonly
  7. * utilized scheme is DER or the "Distinguished Encoding Rules". PEM's are base64 encoded
  8. * DER blobs.
  9. * File_ASN1 decodes and encodes DER formatted messages and places them in a semantic context.
  10. * Uses the 1988 ASN.1 syntax.
  11. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software.
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. * @category File
  28. * @package File_ASN1
  29. * @author Jim Wigginton <terrafrost@php.net>
  30. * @copyright MMXII Jim Wigginton
  31. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  32. * @link http://phpseclib.sourceforge.net
  33. */
  34. /**#@+
  35. * Tag Classes
  36. *
  37. * @access private
  38. * @link http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=12
  39. */
  40. define('FILE_ASN1_CLASS_UNIVERSAL', 0);
  41. define('FILE_ASN1_CLASS_APPLICATION', 1);
  42. define('FILE_ASN1_CLASS_CONTEXT_SPECIFIC', 2);
  43. define('FILE_ASN1_CLASS_PRIVATE', 3);
  44. /**#@-*/
  45. /**#@+
  46. * Tag Classes
  47. *
  48. * @access private
  49. * @link http://www.obj-sys.com/asn1tutorial/node124.html
  50. */
  51. define('FILE_ASN1_TYPE_BOOLEAN', 1);
  52. define('FILE_ASN1_TYPE_INTEGER', 2);
  53. define('FILE_ASN1_TYPE_BIT_STRING', 3);
  54. define('FILE_ASN1_TYPE_OCTET_STRING', 4);
  55. define('FILE_ASN1_TYPE_NULL', 5);
  56. define('FILE_ASN1_TYPE_OBJECT_IDENTIFIER', 6);
  57. //define('FILE_ASN1_TYPE_OBJECT_DESCRIPTOR',7);
  58. //define('FILE_ASN1_TYPE_INSTANCE_OF', 8); // EXTERNAL
  59. define('FILE_ASN1_TYPE_REAL', 9);
  60. define('FILE_ASN1_TYPE_ENUMERATED', 10);
  61. //define('FILE_ASN1_TYPE_EMBEDDED', 11);
  62. define('FILE_ASN1_TYPE_UTF8_STRING', 12);
  63. //define('FILE_ASN1_TYPE_RELATIVE_OID', 13);
  64. define('FILE_ASN1_TYPE_SEQUENCE', 16); // SEQUENCE OF
  65. define('FILE_ASN1_TYPE_SET', 17); // SET OF
  66. /**#@-*/
  67. /**#@+
  68. * More Tag Classes
  69. *
  70. * @access private
  71. * @link http://www.obj-sys.com/asn1tutorial/node10.html
  72. */
  73. define('FILE_ASN1_TYPE_NUMERIC_STRING', 18);
  74. define('FILE_ASN1_TYPE_PRINTABLE_STRING', 19);
  75. define('FILE_ASN1_TYPE_TELETEX_STRING', 20); // T61String
  76. define('FILE_ASN1_TYPE_VIDEOTEX_STRING', 21);
  77. define('FILE_ASN1_TYPE_IA5_STRING', 22);
  78. define('FILE_ASN1_TYPE_UTC_TIME', 23);
  79. define('FILE_ASN1_TYPE_GENERALIZED_TIME', 24);
  80. define('FILE_ASN1_TYPE_GRAPHIC_STRING', 25);
  81. define('FILE_ASN1_TYPE_VISIBLE_STRING', 26); // ISO646String
  82. define('FILE_ASN1_TYPE_GENERAL_STRING', 27);
  83. define('FILE_ASN1_TYPE_UNIVERSAL_STRING', 28);
  84. //define('FILE_ASN1_TYPE_CHARACTER_STRING',29);
  85. define('FILE_ASN1_TYPE_BMP_STRING', 30);
  86. /**#@-*/
  87. /**#@+
  88. * Tag Aliases
  89. * These tags are kinda place holders for other tags.
  90. *
  91. * @access private
  92. */
  93. define('FILE_ASN1_TYPE_CHOICE', -1);
  94. define('FILE_ASN1_TYPE_ANY', -2);
  95. /**#@-*/
  96. /**
  97. * ASN.1 Element
  98. * Bypass normal encoding rules in File_ASN1::encodeDER()
  99. *
  100. * @author Jim Wigginton <terrafrost@php.net>
  101. * @version 0.3.0
  102. * @access public
  103. * @package File_ASN1
  104. */
  105. class File_ASN1_Element
  106. {
  107. /**
  108. * Raw element value
  109. *
  110. * @var String
  111. * @access private
  112. */
  113. var $element;
  114. /**
  115. * Constructor
  116. *
  117. * @param String $encoded
  118. *
  119. * @return File_ASN1_Element
  120. * @access public
  121. */
  122. function File_ASN1_Element($encoded)
  123. {
  124. $this->element = $encoded;
  125. }
  126. }
  127. /**
  128. * Pure-PHP ASN.1 Parser
  129. *
  130. * @author Jim Wigginton <terrafrost@php.net>
  131. * @version 0.3.0
  132. * @access public
  133. * @package File_ASN1
  134. */
  135. class File_ASN1
  136. {
  137. /**
  138. * ASN.1 object identifier
  139. *
  140. * @var Array
  141. * @access private
  142. * @link http://en.wikipedia.org/wiki/Object_identifier
  143. */
  144. var $oids = array();
  145. /**
  146. * Default date format
  147. *
  148. * @var String
  149. * @access private
  150. * @link http://php.net/class.datetime
  151. */
  152. var $format = 'D, d M y H:i:s O';
  153. /**
  154. * Default date format
  155. *
  156. * @var Array
  157. * @access private
  158. * @see File_ASN1::setTimeFormat()
  159. * @see File_ASN1::asn1map()
  160. * @link http://php.net/class.datetime
  161. */
  162. var $encoded;
  163. /**
  164. * Filters
  165. * If the mapping type is FILE_ASN1_TYPE_ANY what do we actually encode it as?
  166. *
  167. * @var Array
  168. * @access private
  169. * @see File_ASN1::_encode_der()
  170. */
  171. var $filters;
  172. /**
  173. * Type mapping table for the ANY type.
  174. * Structured or unknown types are mapped to a FILE_ASN1_Element.
  175. * Unambiguous types get the direct mapping (int/real/bool).
  176. * Others are mapped as a choice, with an extra indexing level.
  177. *
  178. * @var Array
  179. * @access public
  180. */
  181. var $ANYmap = array(
  182. FILE_ASN1_TYPE_BOOLEAN => true,
  183. FILE_ASN1_TYPE_INTEGER => true,
  184. FILE_ASN1_TYPE_BIT_STRING => 'bitString',
  185. FILE_ASN1_TYPE_OCTET_STRING => 'octetString',
  186. FILE_ASN1_TYPE_NULL => 'null',
  187. FILE_ASN1_TYPE_OBJECT_IDENTIFIER => 'objectIdentifier',
  188. FILE_ASN1_TYPE_REAL => true,
  189. FILE_ASN1_TYPE_ENUMERATED => 'enumerated',
  190. FILE_ASN1_TYPE_UTF8_STRING => 'utf8String',
  191. FILE_ASN1_TYPE_NUMERIC_STRING => 'numericString',
  192. FILE_ASN1_TYPE_PRINTABLE_STRING => 'printableString',
  193. FILE_ASN1_TYPE_TELETEX_STRING => 'teletexString',
  194. FILE_ASN1_TYPE_VIDEOTEX_STRING => 'videotexString',
  195. FILE_ASN1_TYPE_IA5_STRING => 'ia5String',
  196. FILE_ASN1_TYPE_UTC_TIME => 'utcTime',
  197. FILE_ASN1_TYPE_GENERALIZED_TIME => 'generalTime',
  198. FILE_ASN1_TYPE_GRAPHIC_STRING => 'graphicString',
  199. FILE_ASN1_TYPE_VISIBLE_STRING => 'visibleString',
  200. FILE_ASN1_TYPE_GENERAL_STRING => 'generalString',
  201. FILE_ASN1_TYPE_UNIVERSAL_STRING => 'universalString',
  202. //FILE_ASN1_TYPE_CHARACTER_STRING => 'characterString',
  203. FILE_ASN1_TYPE_BMP_STRING => 'bmpString'
  204. );
  205. /**
  206. * String type to character size mapping table.
  207. * Non-convertable types are absent from this table.
  208. * size == 0 indicates variable length encoding.
  209. *
  210. * @var Array
  211. * @access public
  212. */
  213. var $stringTypeSize = array(
  214. FILE_ASN1_TYPE_UTF8_STRING => 0,
  215. FILE_ASN1_TYPE_BMP_STRING => 2,
  216. FILE_ASN1_TYPE_UNIVERSAL_STRING => 4,
  217. FILE_ASN1_TYPE_PRINTABLE_STRING => 1,
  218. FILE_ASN1_TYPE_TELETEX_STRING => 1,
  219. FILE_ASN1_TYPE_IA5_STRING => 1,
  220. FILE_ASN1_TYPE_VISIBLE_STRING => 1,
  221. );
  222. /**
  223. * Default Constructor.
  224. *
  225. * @access public
  226. */
  227. function File_ASN1()
  228. {
  229. static $static_init = null;
  230. if (!$static_init) {
  231. $static_init = true;
  232. if (!class_exists('Math_BigInteger')) {
  233. require_once dirname(__FILE__).'/../Math/BigInteger.php';
  234. }
  235. }
  236. }
  237. /**
  238. * Parse BER-encoding
  239. * Serves a similar purpose to openssl's asn1parse
  240. *
  241. * @param String $encoded
  242. *
  243. * @return Array
  244. * @access public
  245. */
  246. function decodeBER($encoded)
  247. {
  248. if (is_object($encoded) && strtolower(get_class($encoded)) == 'file_asn1_element') {
  249. $encoded = $encoded->element;
  250. }
  251. $this->encoded = $encoded;
  252. return $this->_decode_ber($encoded);
  253. }
  254. /**
  255. * Parse BER-encoding (Helper function)
  256. * Sometimes we want to get the BER encoding of a particular tag. $start lets us do that without having to reencode.
  257. * $encoded is passed by reference for the recursive calls done for FILE_ASN1_TYPE_BIT_STRING and
  258. * FILE_ASN1_TYPE_OCTET_STRING. In those cases, the indefinite length is used.
  259. *
  260. * @param String $encoded
  261. * @param Integer $start
  262. *
  263. * @return Array
  264. * @access private
  265. */
  266. function _decode_ber(&$encoded, $start = 0)
  267. {
  268. $decoded = array();
  269. while (strlen($encoded)) {
  270. $current = array('start' => $start);
  271. $type = ord($this->_string_shift($encoded));
  272. $start++;
  273. $constructed = ($type >> 5) & 1;
  274. $tag = $type & 0x1F;
  275. if ($tag == 0x1F) {
  276. $tag = 0;
  277. // process septets (since the eighth bit is ignored, it's not an octet)
  278. do {
  279. $loop = ord($encoded[0]) >> 7;
  280. $tag <<= 7;
  281. $tag |= ord($this->_string_shift($encoded)) & 0x7F;
  282. $start++;
  283. } while ($loop);
  284. }
  285. // Length, as discussed in paragraph 8.1.3 of X.690-0207.pdf#page=13
  286. $length = ord($this->_string_shift($encoded));
  287. $start++;
  288. if ($length == 0x80) { // indefinite length
  289. // "[A sender shall] use the indefinite form (see 8.1.3.6) if the encoding is constructed and is not all
  290. // immediately available." -- paragraph 8.1.3.2.c
  291. //if ( !$constructed ) {
  292. // return false;
  293. //}
  294. $length = strlen($encoded);
  295. } elseif ($length & 0x80) { // definite length, long form
  296. // technically, the long form of the length can be represented by up to 126 octets (bytes), but we'll only
  297. // support it up to four.
  298. $length &= 0x7F;
  299. $temp = $this->_string_shift($encoded, $length);
  300. // tags of indefinite length don't really have a header length; this length includes the tag
  301. $current += array('headerlength' => $length + 2);
  302. $start += $length;
  303. extract(unpack('Nlength', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)));
  304. } else {
  305. $current += array('headerlength' => 2);
  306. }
  307. // End-of-content, 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
  308. if (!$type && !$length) {
  309. return $decoded;
  310. }
  311. $content = $this->_string_shift($encoded, $length);
  312. /* Class is UNIVERSAL, APPLICATION, PRIVATE, or CONTEXT-SPECIFIC. The UNIVERSAL class is restricted to the ASN.1
  313. built-in types. It defines an application-independent data type that must be distinguishable from all other
  314. data types. The other three classes are user defined. The APPLICATION class distinguishes data types that
  315. have a wide, scattered use within a particular presentation context. PRIVATE distinguishes data types within
  316. a particular organization or country. CONTEXT-SPECIFIC distinguishes members of a sequence or set, the
  317. alternatives of a CHOICE, or universally tagged set members. Only the class number appears in braces for this
  318. data type; the term CONTEXT-SPECIFIC does not appear.
  319. -- http://www.obj-sys.com/asn1tutorial/node12.html */
  320. $class = ($type >> 6) & 3;
  321. switch ($class) {
  322. case FILE_ASN1_CLASS_APPLICATION:
  323. case FILE_ASN1_CLASS_PRIVATE:
  324. case FILE_ASN1_CLASS_CONTEXT_SPECIFIC:
  325. $decoded[] = array(
  326. 'type' => $class,
  327. 'constant' => $tag,
  328. 'content' => $constructed ? $this->_decode_ber($content, $start) : $content,
  329. 'length' => $length + $start - $current['start']
  330. ) + $current;
  331. $start += $length;
  332. continue 2;
  333. }
  334. $current += array('type' => $tag);
  335. // decode UNIVERSAL tags
  336. switch ($tag) {
  337. case FILE_ASN1_TYPE_BOOLEAN:
  338. // "The contents octets shall consist of a single octet." -- paragraph 8.2.1
  339. //if (strlen($content) != 1) {
  340. // return false;
  341. //}
  342. $current['content'] = (bool) ord($content[0]);
  343. break;
  344. case FILE_ASN1_TYPE_INTEGER:
  345. case FILE_ASN1_TYPE_ENUMERATED:
  346. $current['content'] = new Math_BigInteger($content, -256);
  347. break;
  348. case FILE_ASN1_TYPE_REAL: // not currently supported
  349. return false;
  350. case FILE_ASN1_TYPE_BIT_STRING:
  351. // The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit,
  352. // the number of unused bits in the final subsequent octet. The number shall be in the range zero to
  353. // seven.
  354. if (!$constructed) {
  355. $current['content'] = $content;
  356. } else {
  357. $temp = $this->_decode_ber($content, $start);
  358. $length -= strlen($content);
  359. $last = count($temp) - 1;
  360. for ($i = 0; $i < $last; $i++) {
  361. // all subtags should be bit strings
  362. //if ($temp[$i]['type'] != FILE_ASN1_TYPE_BIT_STRING) {
  363. // return false;
  364. //}
  365. $current['content'] .= substr($temp[$i]['content'], 1);
  366. }
  367. // all subtags should be bit strings
  368. //if ($temp[$last]['type'] != FILE_ASN1_TYPE_BIT_STRING) {
  369. // return false;
  370. //}
  371. $current['content'] = $temp[$last]['content'][0].$current['content'].substr($temp[$i]['content'], 1);
  372. }
  373. break;
  374. case FILE_ASN1_TYPE_OCTET_STRING:
  375. if (!$constructed) {
  376. $current['content'] = $content;
  377. } else {
  378. $temp = $this->_decode_ber($content, $start);
  379. $length -= strlen($content);
  380. for ($i = 0, $size = count($temp); $i < $size; $i++) {
  381. // all subtags should be octet strings
  382. //if ($temp[$i]['type'] != FILE_ASN1_TYPE_OCTET_STRING) {
  383. // return false;
  384. //}
  385. $current['content'] .= $temp[$i]['content'];
  386. }
  387. // $length =
  388. }
  389. break;
  390. case FILE_ASN1_TYPE_NULL:
  391. // "The contents octets shall not contain any octets." -- paragraph 8.8.2
  392. //if (strlen($content)) {
  393. // return false;
  394. //}
  395. break;
  396. case FILE_ASN1_TYPE_SEQUENCE:
  397. case FILE_ASN1_TYPE_SET:
  398. $current['content'] = $this->_decode_ber($content, $start);
  399. break;
  400. case FILE_ASN1_TYPE_OBJECT_IDENTIFIER:
  401. $temp = ord($this->_string_shift($content));
  402. $current['content'] = sprintf('%d.%d', floor($temp / 40), $temp % 40);
  403. $valuen = 0;
  404. // process septets
  405. while (strlen($content)) {
  406. $temp = ord($this->_string_shift($content));
  407. $valuen <<= 7;
  408. $valuen |= $temp & 0x7F;
  409. if (~$temp & 0x80) {
  410. $current['content'] .= ".$valuen";
  411. $valuen = 0;
  412. }
  413. }
  414. // the eighth bit of the last byte should not be 1
  415. //if ($temp >> 7) {
  416. // return false;
  417. //}
  418. break;
  419. /* Each character string type shall be encoded as if it had been declared:
  420. [UNIVERSAL x] IMPLICIT OCTET STRING
  421. -- X.690-0207.pdf#page=23 (paragraph 8.21.3)
  422. Per that, we're not going to do any validation. If there are any illegal characters in the string,
  423. we don't really care */
  424. case FILE_ASN1_TYPE_NUMERIC_STRING:
  425. // 0,1,2,3,4,5,6,7,8,9, and space
  426. case FILE_ASN1_TYPE_PRINTABLE_STRING:
  427. // Upper and lower case letters, digits, space, apostrophe, left/right parenthesis, plus sign, comma,
  428. // hyphen, full stop, solidus, colon, equal sign, question mark
  429. case FILE_ASN1_TYPE_TELETEX_STRING:
  430. // The Teletex character set in CCITT's T61, space, and delete
  431. // see http://en.wikipedia.org/wiki/Teletex#Character_sets
  432. case FILE_ASN1_TYPE_VIDEOTEX_STRING:
  433. // The Videotex character set in CCITT's T.100 and T.101, space, and delete
  434. case FILE_ASN1_TYPE_VISIBLE_STRING:
  435. // Printing character sets of international ASCII, and space
  436. case FILE_ASN1_TYPE_IA5_STRING:
  437. // International Alphabet 5 (International ASCII)
  438. case FILE_ASN1_TYPE_GRAPHIC_STRING:
  439. // All registered G sets, and space
  440. case FILE_ASN1_TYPE_GENERAL_STRING:
  441. // All registered C and G sets, space and delete
  442. case FILE_ASN1_TYPE_UTF8_STRING:
  443. // ????
  444. case FILE_ASN1_TYPE_BMP_STRING:
  445. $current['content'] = $content;
  446. break;
  447. case FILE_ASN1_TYPE_UTC_TIME:
  448. case FILE_ASN1_TYPE_GENERALIZED_TIME:
  449. $current['content'] = $this->_decodeTime($content, $tag);
  450. default:
  451. }
  452. $start += $length;
  453. $decoded[] = $current + array('length' => $start - $current['start']);
  454. }
  455. return $decoded;
  456. }
  457. /**
  458. * ASN.1 Decode
  459. * Provides an ASN.1 semantic mapping ($mapping) from a parsed BER-encoding to a human readable format.
  460. *
  461. * @param Array $decoded
  462. * @param Array $mapping
  463. *
  464. * @return Array
  465. * @access public
  466. */
  467. function asn1map($decoded, $mapping)
  468. {
  469. if (isset($mapping['explicit'])) {
  470. $decoded = $decoded['content'][0];
  471. }
  472. switch (true) {
  473. case $mapping['type'] == FILE_ASN1_TYPE_ANY:
  474. $intype = $decoded['type'];
  475. if (isset($decoded['constant']) || !isset($this->ANYmap[$intype]) || ($this->encoded[$decoded['start']] & 0x20)) {
  476. return new File_ASN1_Element(substr($this->encoded, $decoded['start'], $decoded['length']));
  477. }
  478. $inmap = $this->ANYmap[$intype];
  479. if (is_string($inmap)) {
  480. return array($inmap => $this->asn1map($decoded, array('type' => $intype) + $mapping));
  481. }
  482. break;
  483. case $mapping['type'] == FILE_ASN1_TYPE_CHOICE:
  484. foreach ($mapping['children'] as $key => $option) {
  485. switch (true) {
  486. case isset($option['constant']) && $option['constant'] == $decoded['constant']:
  487. case !isset($option['constant']) && $option['type'] == $decoded['type']:
  488. $value = $this->asn1map($decoded, $option);
  489. break;
  490. case !isset($option['constant']) && $option['type'] == FILE_ASN1_TYPE_CHOICE:
  491. $v = $this->asn1map($decoded, $option);
  492. if (isset($v)) {
  493. $value = $v;
  494. }
  495. }
  496. if (isset($value)) {
  497. return array($key => $value);
  498. }
  499. }
  500. return null;
  501. case isset($mapping['implicit']):
  502. case isset($mapping['explicit']):
  503. case $decoded['type'] == $mapping['type']:
  504. break;
  505. default:
  506. return null;
  507. }
  508. if (isset($mapping['implicit'])) {
  509. $decoded['type'] = $mapping['type'];
  510. }
  511. switch ($decoded['type']) {
  512. case FILE_ASN1_TYPE_SEQUENCE:
  513. $map = array();
  514. // ignore the min and max
  515. if (isset($mapping['min']) && isset($mapping['max'])) {
  516. $child = $mapping['children'];
  517. foreach ($decoded['content'] as $content) {
  518. if (($map[] = $this->asn1map($content, $child)) === null) {
  519. return null;
  520. }
  521. }
  522. return $map;
  523. }
  524. $n = count($decoded['content']);
  525. $i = 0;
  526. foreach ($mapping['children'] as $key => $child) {
  527. $maymatch = $i < $n; // Match only existing input.
  528. if ($maymatch) {
  529. $temp = $decoded['content'][$i];
  530. if ($child['type'] != FILE_ASN1_TYPE_CHOICE) {
  531. // Get the mapping and input class & constant.
  532. $childClass = $tempClass = FILE_ASN1_CLASS_UNIVERSAL;
  533. $constant = null;
  534. if (isset($temp['constant'])) {
  535. $tempClass = isset($temp['class']) ? $temp['class'] : FILE_ASN1_CLASS_CONTEXT_SPECIFIC;
  536. }
  537. if (isset($child['class'])) {
  538. $childClass = $child['class'];
  539. $constant = $child['cast'];
  540. } elseif (isset($child['constant'])) {
  541. $childClass = FILE_ASN1_CLASS_CONTEXT_SPECIFIC;
  542. $constant = $child['constant'];
  543. }
  544. if (isset($constant) && isset($temp['constant'])) {
  545. // Can only match if constants and class match.
  546. $maymatch = $constant == $temp['constant'] && $childClass == $tempClass;
  547. } else {
  548. // Can only match if no constant expected and type matches or is generic.
  549. $maymatch = !isset($child['constant']) && array_search($child['type'], array($temp['type'], FILE_ASN1_TYPE_ANY, FILE_ASN1_TYPE_CHOICE)) !== false;
  550. }
  551. }
  552. }
  553. if ($maymatch) {
  554. // Attempt submapping.
  555. $candidate = $this->asn1map($temp, $child);
  556. $maymatch = $candidate !== null;
  557. }
  558. if ($maymatch) {
  559. // Got the match: use it.
  560. $map[$key] = $candidate;
  561. $i++;
  562. } elseif (isset($child['default'])) {
  563. $map[$key] = $child['default']; // Use default.
  564. } elseif (!isset($child['optional'])) {
  565. return null; // Syntax error.
  566. }
  567. }
  568. // Fail mapping if all input items have not been consumed.
  569. return $i < $n ? null : $map;
  570. // the main diff between sets and sequences is the encapsulation of the foreach in another for loop
  571. case FILE_ASN1_TYPE_SET:
  572. $map = array();
  573. // ignore the min and max
  574. if (isset($mapping['min']) && isset($mapping['max'])) {
  575. $child = $mapping['children'];
  576. foreach ($decoded['content'] as $content) {
  577. if (($map[] = $this->asn1map($content, $child)) === null) {
  578. return null;
  579. }
  580. }
  581. return $map;
  582. }
  583. for ($i = 0; $i < count($decoded['content']); $i++) {
  584. $temp = $decoded['content'][$i];
  585. $tempClass = FILE_ASN1_CLASS_UNIVERSAL;
  586. if (isset($temp['constant'])) {
  587. $tempClass = isset($temp['class']) ? $temp['class'] : FILE_ASN1_CLASS_CONTEXT_SPECIFIC;
  588. }
  589. foreach ($mapping['children'] as $key => $child) {
  590. if (isset($map[$key])) {
  591. continue;
  592. }
  593. $maymatch = true;
  594. if ($child['type'] != FILE_ASN1_TYPE_CHOICE) {
  595. $childClass = FILE_ASN1_CLASS_UNIVERSAL;
  596. $constant = null;
  597. if (isset($child['class'])) {
  598. $childClass = $child['class'];
  599. $constant = $child['cast'];
  600. } elseif (isset($child['constant'])) {
  601. $childClass = FILE_ASN1_CLASS_CONTEXT_SPECIFIC;
  602. $constant = $child['constant'];
  603. }
  604. if (isset($constant) && isset($temp['constant'])) {
  605. // Can only match if constants and class match.
  606. $maymatch = $constant == $temp['constant'] && $childClass == $tempClass;
  607. } else {
  608. // Can only match if no constant expected and type matches or is generic.
  609. $maymatch = !isset($child['constant']) && array_search($child['type'], array($temp['type'], FILE_ASN1_TYPE_ANY, FILE_ASN1_TYPE_CHOICE)) !== false;
  610. }
  611. }
  612. if ($maymatch) {
  613. // Attempt submapping.
  614. $candidate = $this->asn1map($temp, $child);
  615. $maymatch = $candidate !== null;
  616. }
  617. if (!$maymatch) {
  618. break;
  619. }
  620. // Got the match: use it.
  621. $map[$key] = $candidate;
  622. break;
  623. }
  624. }
  625. foreach ($mapping['children'] as $key => $child) {
  626. if (!isset($map[$key])) {
  627. if (isset($child['default'])) {
  628. $map[$key] = $child['default'];
  629. } elseif (!isset($child['optional'])) {
  630. return null;
  631. }
  632. }
  633. }
  634. return $map;
  635. case FILE_ASN1_TYPE_OBJECT_IDENTIFIER:
  636. return isset($this->oids[$decoded['content']]) ? $this->oids[$decoded['content']] : $decoded['content'];
  637. case FILE_ASN1_TYPE_UTC_TIME:
  638. case FILE_ASN1_TYPE_GENERALIZED_TIME:
  639. if (isset($mapping['implicit'])) {
  640. $decoded['content'] = $this->_decodeTime($decoded['content'], $decoded['type']);
  641. }
  642. return @date($this->format, $decoded['content']);
  643. case FILE_ASN1_TYPE_BIT_STRING:
  644. if (isset($mapping['mapping'])) {
  645. $offset = ord($decoded['content'][0]);
  646. $size = (strlen($decoded['content']) - 1) * 8 - $offset;
  647. /*
  648. From X.680-0207.pdf#page=46 (21.7):
  649. "When a "NamedBitList" is used in defining a bitstring type ASN.1 encoding rules are free to add (or remove)
  650. arbitrarily any trailing 0 bits to (or from) values that are being encoded or decoded. Application designers should
  651. therefore ensure that different semantics are not associated with such values which differ only in the number of trailing
  652. 0 bits."
  653. */
  654. $bits = count($mapping['mapping']) == $size ? array() : array_fill(0, count($mapping['mapping']) - $size, false);
  655. for ($i = strlen($decoded['content']) - 1; $i > 0; $i--) {
  656. $current = ord($decoded['content'][$i]);
  657. for ($j = $offset; $j < 8; $j++) {
  658. $bits[] = (bool) ($current & (1 << $j));
  659. }
  660. $offset = 0;
  661. }
  662. $values = array();
  663. $map = array_reverse($mapping['mapping']);
  664. foreach ($map as $i => $value) {
  665. if ($bits[$i]) {
  666. $values[] = $value;
  667. }
  668. }
  669. return $values;
  670. }
  671. case FILE_ASN1_TYPE_OCTET_STRING:
  672. return base64_encode($decoded['content']);
  673. case FILE_ASN1_TYPE_NULL:
  674. return '';
  675. case FILE_ASN1_TYPE_BOOLEAN:
  676. return $decoded['content'];
  677. case FILE_ASN1_TYPE_NUMERIC_STRING:
  678. case FILE_ASN1_TYPE_PRINTABLE_STRING:
  679. case FILE_ASN1_TYPE_TELETEX_STRING:
  680. case FILE_ASN1_TYPE_VIDEOTEX_STRING:
  681. case FILE_ASN1_TYPE_IA5_STRING:
  682. case FILE_ASN1_TYPE_GRAPHIC_STRING:
  683. case FILE_ASN1_TYPE_VISIBLE_STRING:
  684. case FILE_ASN1_TYPE_GENERAL_STRING:
  685. case FILE_ASN1_TYPE_UNIVERSAL_STRING:
  686. case FILE_ASN1_TYPE_UTF8_STRING:
  687. case FILE_ASN1_TYPE_BMP_STRING:
  688. return $decoded['content'];
  689. case FILE_ASN1_TYPE_INTEGER:
  690. case FILE_ASN1_TYPE_ENUMERATED:
  691. $temp = $decoded['content'];
  692. if (isset($mapping['implicit'])) {
  693. $temp = new Math_BigInteger($decoded['content'], -256);
  694. }
  695. if (isset($mapping['mapping'])) {
  696. $temp = (int) $temp->toString();
  697. return isset($mapping['mapping'][$temp]) ?
  698. $mapping['mapping'][$temp] :
  699. false;
  700. }
  701. return $temp;
  702. }
  703. }
  704. /**
  705. * ASN.1 Encode
  706. * DER-encodes an ASN.1 semantic mapping ($mapping). Some libraries would probably call this function
  707. * an ASN.1 compiler.
  708. *
  709. * @param String $source
  710. * @param String $mapping
  711. * @param Integer $idx
  712. *
  713. * @return String
  714. * @access public
  715. */
  716. function encodeDER($source, $mapping)
  717. {
  718. $this->location = array();
  719. return $this->_encode_der($source, $mapping);
  720. }
  721. /**
  722. * ASN.1 Encode (Helper function)
  723. *
  724. * @param String $source
  725. * @param String $mapping
  726. * @param Integer $idx
  727. *
  728. * @return String
  729. * @access private
  730. */
  731. function _encode_der($source, $mapping, $idx = null)
  732. {
  733. if (is_object($source) && strtolower(get_class($source)) == 'file_asn1_element') {
  734. return $source->element;
  735. }
  736. // do not encode (implicitly optional) fields with value set to default
  737. if (isset($mapping['default']) && $source === $mapping['default']) {
  738. return '';
  739. }
  740. if (isset($idx)) {
  741. $this->location[] = $idx;
  742. }
  743. $tag = $mapping['type'];
  744. switch ($tag) {
  745. case FILE_ASN1_TYPE_SET: // Children order is not important, thus process in sequence.
  746. case FILE_ASN1_TYPE_SEQUENCE:
  747. $tag |= 0x20; // set the constructed bit
  748. $value = '';
  749. // ignore the min and max
  750. if (isset($mapping['min']) && isset($mapping['max'])) {
  751. $child = $mapping['children'];
  752. foreach ($source as $content) {
  753. $temp = $this->_encode_der($content, $child);
  754. if ($temp === false) {
  755. return false;
  756. }
  757. $value .= $temp;
  758. }
  759. break;
  760. }
  761. foreach ($mapping['children'] as $key => $child) {
  762. if (!isset($source[$key])) {
  763. if (!isset($child['optional'])) {
  764. return false;
  765. }
  766. continue;
  767. }
  768. $temp = $this->_encode_der($source[$key], $child, $key);
  769. if ($temp === false) {
  770. return false;
  771. }
  772. // An empty child encoding means it has been optimized out.
  773. // Else we should have at least one tag byte.
  774. if ($temp === '') {
  775. continue;
  776. }
  777. // if isset($child['constant']) is true then isset($child['optional']) should be true as well
  778. if (isset($child['constant'])) {
  779. /*
  780. From X.680-0207.pdf#page=58 (30.6):
  781. "The tagging construction specifies explicit tagging if any of the following holds:
  782. ...
  783. c) the "Tag Type" alternative is used and the value of "TagDefault" for the module is IMPLICIT TAGS or
  784. AUTOMATIC TAGS, but the type defined by "Type" is an untagged choice type, an untagged open type, or
  785. an untagged "DummyReference" (see ITU-T Rec. X.683 | ISO/IEC 8824-4, 8.3)."
  786. */
  787. if (isset($child['explicit']) || $child['type'] == FILE_ASN1_TYPE_CHOICE) {
  788. $subtag = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | 0x20 | $child['constant']);
  789. $temp = $subtag.$this->_encodeLength(strlen($temp)).$temp;
  790. } else {
  791. $subtag = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | (ord($temp[0]) & 0x20) | $child['constant']);
  792. $temp = $subtag.substr($temp, 1);
  793. }
  794. }
  795. $value .= $temp;
  796. }
  797. break;
  798. case FILE_ASN1_TYPE_CHOICE:
  799. $temp = false;
  800. foreach ($mapping['children'] as $key => $child) {
  801. if (!isset($source[$key])) {
  802. continue;
  803. }
  804. $temp = $this->_encode_der($source[$key], $child, $key);
  805. if ($temp === false) {
  806. return false;
  807. }
  808. // An empty child encoding means it has been optimized out.
  809. // Else we should have at least one tag byte.
  810. if ($temp === '') {
  811. continue;
  812. }
  813. $tag = ord($temp[0]);
  814. // if isset($child['constant']) is true then isset($child['optional']) should be true as well
  815. if (isset($child['constant'])) {
  816. if (isset($child['explicit']) || $child['type'] == FILE_ASN1_TYPE_CHOICE) {
  817. $subtag = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | 0x20 | $child['constant']);
  818. $temp = $subtag.$this->_encodeLength(strlen($temp)).$temp;
  819. } else {
  820. $subtag = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | (ord($temp[0]) & 0x20) | $child['constant']);
  821. $temp = $subtag.substr($temp, 1);
  822. }
  823. }
  824. }
  825. if (isset($idx)) {
  826. array_pop($this->location);
  827. }
  828. if ($temp && isset($mapping['cast'])) {
  829. $temp[0] = chr(($mapping['class'] << 6) | ($tag & 0x20) | $mapping['cast']);
  830. }
  831. return $temp;
  832. case FILE_ASN1_TYPE_INTEGER:
  833. case FILE_ASN1_TYPE_ENUMERATED:
  834. if (!isset($mapping['mapping'])) {
  835. $value = $source->toBytes(true);
  836. } else {
  837. $value = array_search($source, $mapping['mapping']);
  838. if ($value === false) {
  839. return false;
  840. }
  841. $value = new Math_BigInteger($value);
  842. $value = $value->toBytes(true);
  843. if (!strlen($value)) {
  844. $value = chr(0);
  845. }
  846. }
  847. break;
  848. case FILE_ASN1_TYPE_UTC_TIME:
  849. case FILE_ASN1_TYPE_GENERALIZED_TIME:
  850. $format = $mapping['type'] == FILE_ASN1_TYPE_UTC_TIME ? 'y' : 'Y';
  851. $format .= 'mdHis';
  852. $value = @gmdate($format, strtotime($source)).'Z';
  853. break;
  854. case FILE_ASN1_TYPE_BIT_STRING:
  855. if (isset($mapping['mapping'])) {
  856. $bits = array_fill(0, count($mapping['mapping']), 0);
  857. $size = 0;
  858. for ($i = 0; $i < count($mapping['mapping']); $i++) {
  859. if (in_array($mapping['mapping'][$i], $source)) {
  860. $bits[$i] = 1;
  861. $size = $i;
  862. }
  863. }
  864. $offset = 8 - (($size + 1) & 7);
  865. $offset = $offset !== 8 ? $offset : 0;
  866. $value = chr($offset);
  867. for ($i = $size + 1; $i < count($mapping['mapping']); $i++) {
  868. unset($bits[$i]);
  869. }
  870. $bits = implode('', array_pad($bits, $size + $offset + 1, 0));
  871. $bytes = explode(' ', rtrim(chunk_split($bits, 8, ' ')));
  872. foreach ($bytes as $byte) {
  873. $value .= chr(bindec($byte));
  874. }
  875. break;
  876. }
  877. case FILE_ASN1_TYPE_OCTET_STRING:
  878. /* The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit,
  879. the number of unused bits in the final subsequent octet. The number shall be in the range zero to seven.
  880. -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=16 */
  881. $value = base64_decode($source);
  882. break;
  883. case FILE_ASN1_TYPE_OBJECT_IDENTIFIER:
  884. $oid = preg_match('#(?:\d+\.)+#', $source) ? $source : array_search($source, $this->oids);
  885. if ($oid === false) {
  886. user_error('Invalid OID');
  887. return false;
  888. }
  889. $value = '';
  890. $parts = explode('.', $oid);
  891. $value = chr(40 * $parts[0] + $parts[1]);
  892. for ($i = 2; $i < count($parts); $i++) {
  893. $temp = '';
  894. if (!$parts[$i]) {
  895. $temp = "\0";
  896. } else {
  897. while ($parts[$i]) {
  898. $temp = chr(0x80 | ($parts[$i] & 0x7F)).$temp;
  899. $parts[$i] >>= 7;
  900. }
  901. $temp[strlen($temp) - 1] = $temp[strlen($temp) - 1] & chr(0x7F);
  902. }
  903. $value .= $temp;
  904. }
  905. break;
  906. case FILE_ASN1_TYPE_ANY:
  907. $loc = $this->location;
  908. if (isset($idx)) {
  909. array_pop($this->location);
  910. }
  911. switch (true) {
  912. case !isset($source):
  913. return $this->_encode_der(null, array('type' => FILE_ASN1_TYPE_NULL) + $mapping);
  914. case is_int($source):
  915. case is_object($source) && strtolower(get_class($source)) == 'math_biginteger':
  916. return $this->_encode_der($source, array('type' => FILE_ASN1_TYPE_INTEGER) + $mapping);
  917. case is_float($source):
  918. return $this->_encode_der($source, array('type' => FILE_ASN1_TYPE_REAL) + $mapping);
  919. case is_bool($source):
  920. return $this->_encode_der($source, array('type' => FILE_ASN1_TYPE_BOOLEAN) + $mapping);
  921. case is_array($source) && count($source) == 1:
  922. $typename = implode('', array_keys($source));
  923. $outtype = array_search($typename, $this->ANYmap, true);
  924. if ($outtype !== false) {
  925. return $this->_encode_der($source[$typename], array('type' => $outtype) + $mapping);
  926. }
  927. }
  928. $filters = $this->filters;
  929. foreach ($loc as $part) {
  930. if (!isset($filters[$part])) {
  931. $filters = false;
  932. break;
  933. }
  934. $filters = $filters[$part];
  935. }
  936. if ($filters === false) {
  937. user_error('No filters defined for '.implode('/', $loc));
  938. return false;
  939. }
  940. return $this->_encode_der($source, $filters + $mapping);
  941. case FILE_ASN1_TYPE_NULL:
  942. $value = '';
  943. break;
  944. case FILE_ASN1_TYPE_NUMERIC_STRING:
  945. case FILE_ASN1_TYPE_TELETEX_STRING:
  946. case FILE_ASN1_TYPE_PRINTABLE_STRING:
  947. case FILE_ASN1_TYPE_UNIVERSAL_STRING:
  948. case FILE_ASN1_TYPE_UTF8_STRING:
  949. case FILE_ASN1_TYPE_BMP_STRING:
  950. case FILE_ASN1_TYPE_IA5_STRING:
  951. case FILE_ASN1_TYPE_VISIBLE_STRING:
  952. case FILE_ASN1_TYPE_VIDEOTEX_STRING:
  953. case FILE_ASN1_TYPE_GRAPHIC_STRING:
  954. case FILE_ASN1_TYPE_GENERAL_STRING:
  955. $value = $source;
  956. break;
  957. case FILE_ASN1_TYPE_BOOLEAN:
  958. $value = $source ? "\xFF" : "\x00";
  959. break;
  960. default:
  961. user_error('Mapping provides no type definition for '.implode('/', $this->location));
  962. return false;
  963. }
  964. if (isset($idx)) {
  965. array_pop($this->location);
  966. }
  967. if (isset($mapping['cast'])) {
  968. $tag = ($mapping['class'] << 6) | ($tag & 0x20) | $mapping['cast'];
  969. }
  970. return chr($tag).$this->_encodeLength(strlen($value)).$value;
  971. }
  972. /**
  973. * DER-encode the length
  974. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  975. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  976. *
  977. * @access private
  978. *
  979. * @param Integer $length
  980. *
  981. * @return String
  982. */
  983. function _encodeLength($length)
  984. {
  985. if ($length <= 0x7F) {
  986. return chr($length);
  987. }
  988. $temp = ltrim(pack('N', $length), chr(0));
  989. return pack('Ca*', 0x80 | strlen($temp), $temp);
  990. }
  991. /**
  992. * BER-decode the time
  993. * Called by _decode_ber() and in the case of implicit tags asn1map().
  994. *
  995. * @access private
  996. *
  997. * @param String $content
  998. * @param Integer $tag
  999. *
  1000. * @return String
  1001. */
  1002. function _decodeTime($content, $tag)
  1003. {
  1004. /* UTCTime:
  1005. http://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
  1006. http://www.obj-sys.com/asn1tutorial/node15.html
  1007. GeneralizedTime:
  1008. http://tools.ietf.org/html/rfc5280#section-4.1.2.5.2
  1009. http://www.obj-sys.com/asn1tutorial/node14.html */
  1010. $pattern = $tag == FILE_ASN1_TYPE_UTC_TIME ?
  1011. '#(..)(..)(..)(..)(..)(..)(.*)#' :
  1012. '#(....)(..)(..)(..)(..)(..).*([Z+-].*)$#';
  1013. preg_match($pattern, $content, $matches);
  1014. list(, $year, $month, $day, $hour, $minute, $second, $timezone) = $matches;
  1015. if ($tag == FILE_ASN1_TYPE_UTC_TIME) {
  1016. $year = $year >= 50 ? "19$year" : "20$year";
  1017. }
  1018. if ($timezone == 'Z') {
  1019. $mktime = 'gmmktime';
  1020. $timezone = 0;
  1021. } elseif (preg_match('#([+-])(\d\d)(\d\d)#', $timezone, $matches)) {
  1022. $mktime = 'gmmktime';
  1023. $timezone = 60 * $matches[3] + 3600 * $matches[2];
  1024. if ($matches[1] == '-') {
  1025. $timezone = -$timezone;
  1026. }
  1027. } else {
  1028. $mktime = 'mktime';
  1029. $timezone = 0;
  1030. }
  1031. return @$mktime($hour, $minute, $second, $month, $day, $year) + $timezone;
  1032. }
  1033. /**
  1034. * Set the time format
  1035. * Sets the time / date format for asn1map().
  1036. *
  1037. * @access public
  1038. *
  1039. * @param String $format
  1040. */
  1041. function setTimeFormat($format)
  1042. {
  1043. $this->format = $format;
  1044. }
  1045. /**
  1046. * Load OIDs
  1047. * Load the relevant OIDs for a particular ASN.1 semantic mapping.
  1048. *
  1049. * @access public
  1050. *
  1051. * @param Array $oids
  1052. */
  1053. function loadOIDs($oids)
  1054. {
  1055. $this->oids = $oids;
  1056. }
  1057. /**
  1058. * Load filters
  1059. * See File_X509, etc, for an example.
  1060. *
  1061. * @access public
  1062. *
  1063. * @param Array $filters
  1064. */
  1065. function loadFilters($filters)
  1066. {
  1067. $this->filters = $filters;
  1068. }
  1069. /**
  1070. * String Shift
  1071. * Inspired by array_shift
  1072. *
  1073. * @param String $string
  1074. * @param optional Integer $index
  1075. *
  1076. * @return String
  1077. * @access private
  1078. */
  1079. function _string_shift(&$string, $index = 1)
  1080. {
  1081. $substr = substr($string, 0, $index);
  1082. $string = substr($string, $index);
  1083. return $substr;
  1084. }
  1085. /**
  1086. * String type conversion
  1087. * This is a lazy conversion, dealing only with character size.
  1088. * No real conversion table is used.
  1089. *
  1090. * @param String $in
  1091. * @param optional Integer $from
  1092. * @param optional Integer $to
  1093. *
  1094. * @return String
  1095. * @access public
  1096. */
  1097. function convert($in, $from = FILE_ASN1_TYPE_UTF8_STRING, $to = FILE_ASN1_TYPE_UTF8_STRING)
  1098. {
  1099. if (!isset($this->stringTypeSize[$from]) || !isset($this->stringTypeSize[$to])) {
  1100. return false;
  1101. }
  1102. $insize = $this->stringTypeSize[$from];
  1103. $outsize = $this->stringTypeSize[$to];
  1104. $inlength = strlen($in);
  1105. $out = '';
  1106. for ($i = 0; $i < $inlength;) {
  1107. if ($inlength - $i < $insize) {
  1108. return false;
  1109. }
  1110. // Get an input character as a 32-bit value.
  1111. $c = ord($in[$i++]);
  1112. switch (true) {
  1113. case $insize == 4:
  1114. $c = ($c << 8) | ord($in[$i++]);
  1115. $c = ($c << 8) | ord($in[$i++]);
  1116. case $insize == 2:
  1117. $c = ($c << 8) | ord($in[$i++]);
  1118. case $insize == 1:
  1119. break;
  1120. case ($c & 0x80) == 0x00:
  1121. break;
  1122. case ($c & 0x40) == 0x00:
  1123. return false;
  1124. default:
  1125. $bit = 6;
  1126. do {
  1127. if ($bit > 25 || $i >= $inlength || (ord($in[$i]) & 0xC0) != 0x80) {
  1128. return false;
  1129. }
  1130. $c = ($c << 6) | (ord($in[$i++]) & 0x3F);
  1131. $bit += 5;
  1132. $mask = 1 << $bit;
  1133. } while ($c & $bit);
  1134. $c &= $mask - 1;
  1135. break;
  1136. }
  1137. // Convert and append the character to output string.
  1138. $v = '';
  1139. switch (true) {
  1140. case $outsize == 4:
  1141. $v .= chr($c & 0xFF);
  1142. $c >>= 8;
  1143. $v .= chr($c & 0xFF);
  1144. $c >>= 8;
  1145. case $outsize == 2:
  1146. $v .= chr($c & 0xFF);
  1147. $c >>= 8;
  1148. case $outsize == 1:
  1149. $v .= chr($c & 0xFF);
  1150. $c >>= 8;
  1151. if ($c) {
  1152. return false;
  1153. }
  1154. break;
  1155. case ($c & 0x80000000) != 0:
  1156. return false;
  1157. case $c >= 0x04000000:
  1158. $v .= chr(0x80 | ($c & 0x3F));
  1159. $c = ($c >> 6) | 0x04000000;
  1160. case $c >= 0x00200000:
  1161. $v .= chr(0x80 | ($c & 0x3F));
  1162. $c = ($c >> 6) | 0x00200000;
  1163. case $c >= 0x00010000:
  1164. $v .= chr(0x80 | ($c & 0x3F));
  1165. $c = ($c >> 6) | 0x00010000;
  1166. case $c >= 0x00000800:
  1167. $v .= chr(0x80 | ($c & 0x3F));
  1168. $c = ($c >> 6) | 0x00000800;
  1169. case $c >= 0x00000080:
  1170. $v .= chr(0x80 | ($c & 0x3F));
  1171. $c = ($c >> 6) | 0x000000C0;
  1172. default:
  1173. $v .= chr($c);
  1174. break;
  1175. }
  1176. $out .= strrev($v);
  1177. }
  1178. return $out;
  1179. }
  1180. }