ASN1.php 53 KB

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