ASN1.php 50 KB

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