asn1.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  1. /**
  2. * Javascript implementation of Abstract Syntax Notation Number One.
  3. *
  4. * @author Dave Longley
  5. *
  6. * Copyright (c) 2010-2015 Digital Bazaar, Inc.
  7. *
  8. * An API for storing data using the Abstract Syntax Notation Number One
  9. * format using DER (Distinguished Encoding Rules) encoding. This encoding is
  10. * commonly used to store data for PKI, i.e. X.509 Certificates, and this
  11. * implementation exists for that purpose.
  12. *
  13. * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract
  14. * syntax of information without restricting the way the information is encoded
  15. * for transmission. It provides a standard that allows for open systems
  16. * communication. ASN.1 defines the syntax of information data and a number of
  17. * simple data types as well as a notation for describing them and specifying
  18. * values for them.
  19. *
  20. * The RSA algorithm creates public and private keys that are often stored in
  21. * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This
  22. * class provides the most basic functionality required to store and load DSA
  23. * keys that are encoded according to ASN.1.
  24. *
  25. * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)
  26. * and DER (Distinguished Encoding Rules). DER is just a subset of BER that
  27. * has stricter requirements for how data must be encoded.
  28. *
  29. * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)
  30. * and a byte array for the value of this ASN1 structure which may be data or a
  31. * list of ASN.1 structures.
  32. *
  33. * Each ASN.1 structure using BER is (Tag-Length-Value):
  34. *
  35. * | byte 0 | bytes X | bytes Y |
  36. * |--------|---------|----------
  37. * | tag | length | value |
  38. *
  39. * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to
  40. * be two or more octets, but that is not supported by this class. A tag is
  41. * only 1 byte. Bits 1-5 give the tag number (ie the data type within a
  42. * particular 'class'), 6 indicates whether or not the ASN.1 value is
  43. * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If
  44. * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,
  45. * then the class is APPLICATION. If only bit 8 is set, then the class is
  46. * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.
  47. * The tag numbers for the data types for the class UNIVERSAL are listed below:
  48. *
  49. * UNIVERSAL 0 Reserved for use by the encoding rules
  50. * UNIVERSAL 1 Boolean type
  51. * UNIVERSAL 2 Integer type
  52. * UNIVERSAL 3 Bitstring type
  53. * UNIVERSAL 4 Octetstring type
  54. * UNIVERSAL 5 Null type
  55. * UNIVERSAL 6 Object identifier type
  56. * UNIVERSAL 7 Object descriptor type
  57. * UNIVERSAL 8 External type and Instance-of type
  58. * UNIVERSAL 9 Real type
  59. * UNIVERSAL 10 Enumerated type
  60. * UNIVERSAL 11 Embedded-pdv type
  61. * UNIVERSAL 12 UTF8String type
  62. * UNIVERSAL 13 Relative object identifier type
  63. * UNIVERSAL 14-15 Reserved for future editions
  64. * UNIVERSAL 16 Sequence and Sequence-of types
  65. * UNIVERSAL 17 Set and Set-of types
  66. * UNIVERSAL 18-22, 25-30 Character string types
  67. * UNIVERSAL 23-24 Time types
  68. *
  69. * The length of an ASN.1 structure is specified after the tag identifier.
  70. * There is a definite form and an indefinite form. The indefinite form may
  71. * be used if the encoding is constructed and not all immediately available.
  72. * The indefinite form is encoded using a length byte with only the 8th bit
  73. * set. The end of the constructed object is marked using end-of-contents
  74. * octets (two zero bytes).
  75. *
  76. * The definite form looks like this:
  77. *
  78. * The length may take up 1 or more bytes, it depends on the length of the
  79. * value of the ASN.1 structure. DER encoding requires that if the ASN.1
  80. * structure has a value that has a length greater than 127, more than 1 byte
  81. * will be used to store its length, otherwise just one byte will be used.
  82. * This is strict.
  83. *
  84. * In the case that the length of the ASN.1 value is less than 127, 1 octet
  85. * (byte) is used to store the "short form" length. The 8th bit has a value of
  86. * 0 indicating the length is "short form" and not "long form" and bits 7-1
  87. * give the length of the data. (The 8th bit is the left-most, most significant
  88. * bit: also known as big endian or network format).
  89. *
  90. * In the case that the length of the ASN.1 value is greater than 127, 2 to
  91. * 127 octets (bytes) are used to store the "long form" length. The first
  92. * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1
  93. * give the number of additional octets. All following octets are in base 256
  94. * with the most significant digit first (typical big-endian binary unsigned
  95. * integer storage). So, for instance, if the length of a value was 257, the
  96. * first byte would be set to:
  97. *
  98. * 10000010 = 130 = 0x82.
  99. *
  100. * This indicates there are 2 octets (base 256) for the length. The second and
  101. * third bytes (the octets just mentioned) would store the length in base 256:
  102. *
  103. * octet 2: 00000001 = 1 * 256^1 = 256
  104. * octet 3: 00000001 = 1 * 256^0 = 1
  105. * total = 257
  106. *
  107. * The algorithm for converting a js integer value of 257 to base-256 is:
  108. *
  109. * var value = 257;
  110. * var bytes = [];
  111. * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first
  112. * bytes[1] = value & 0xFF; // least significant byte last
  113. *
  114. * On the ASN.1 UNIVERSAL Object Identifier (OID) type:
  115. *
  116. * An OID can be written like: "value1.value2.value3...valueN"
  117. *
  118. * The DER encoding rules:
  119. *
  120. * The first byte has the value 40 * value1 + value2.
  121. * The following bytes, if any, encode the remaining values. Each value is
  122. * encoded in base 128, most significant digit first (big endian), with as
  123. * few digits as possible, and the most significant bit of each byte set
  124. * to 1 except the last in each value's encoding. For example: Given the
  125. * OID "1.2.840.113549", its DER encoding is (remember each byte except the
  126. * last one in each encoding is OR'd with 0x80):
  127. *
  128. * byte 1: 40 * 1 + 2 = 42 = 0x2A.
  129. * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648
  130. * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D
  131. *
  132. * The final value is: 0x2A864886F70D.
  133. * The full OID (including ASN.1 tag and length of 6 bytes) is:
  134. * 0x06062A864886F70D
  135. */
  136. var forge = require('./forge');
  137. require('./util');
  138. require('./oids');
  139. /* ASN.1 API */
  140. var asn1 = module.exports = forge.asn1 = forge.asn1 || {};
  141. /**
  142. * ASN.1 classes.
  143. */
  144. asn1.Class = {
  145. UNIVERSAL: 0x00,
  146. APPLICATION: 0x40,
  147. CONTEXT_SPECIFIC: 0x80,
  148. PRIVATE: 0xC0
  149. };
  150. /**
  151. * ASN.1 types. Not all types are supported by this implementation, only
  152. * those necessary to implement a simple PKI are implemented.
  153. */
  154. asn1.Type = {
  155. NONE: 0,
  156. BOOLEAN: 1,
  157. INTEGER: 2,
  158. BITSTRING: 3,
  159. OCTETSTRING: 4,
  160. NULL: 5,
  161. OID: 6,
  162. ODESC: 7,
  163. EXTERNAL: 8,
  164. REAL: 9,
  165. ENUMERATED: 10,
  166. EMBEDDED: 11,
  167. UTF8: 12,
  168. ROID: 13,
  169. SEQUENCE: 16,
  170. SET: 17,
  171. PRINTABLESTRING: 19,
  172. IA5STRING: 22,
  173. UTCTIME: 23,
  174. GENERALIZEDTIME: 24,
  175. BMPSTRING: 30
  176. };
  177. /**
  178. * Creates a new asn1 object.
  179. *
  180. * @param tagClass the tag class for the object.
  181. * @param type the data type (tag number) for the object.
  182. * @param constructed true if the asn1 object is in constructed form.
  183. * @param value the value for the object, if it is not constructed.
  184. * @param [options] the options to use:
  185. * [bitStringContents] the plain BIT STRING content including padding
  186. * byte.
  187. *
  188. * @return the asn1 object.
  189. */
  190. asn1.create = function(tagClass, type, constructed, value, options) {
  191. /* An asn1 object has a tagClass, a type, a constructed flag, and a
  192. value. The value's type depends on the constructed flag. If
  193. constructed, it will contain a list of other asn1 objects. If not,
  194. it will contain the ASN.1 value as an array of bytes formatted
  195. according to the ASN.1 data type. */
  196. // remove undefined values
  197. if(forge.util.isArray(value)) {
  198. var tmp = [];
  199. for(var i = 0; i < value.length; ++i) {
  200. if(value[i] !== undefined) {
  201. tmp.push(value[i]);
  202. }
  203. }
  204. value = tmp;
  205. }
  206. var obj = {
  207. tagClass: tagClass,
  208. type: type,
  209. constructed: constructed,
  210. composed: constructed || forge.util.isArray(value),
  211. value: value
  212. };
  213. if(options && 'bitStringContents' in options) {
  214. // TODO: copy byte buffer if it's a buffer not a string
  215. obj.bitStringContents = options.bitStringContents;
  216. // TODO: add readonly flag to avoid this overhead
  217. // save copy to detect changes
  218. obj.original = asn1.copy(obj);
  219. }
  220. return obj;
  221. };
  222. /**
  223. * Copies an asn1 object.
  224. *
  225. * @param obj the asn1 object.
  226. * @param [options] copy options:
  227. * [excludeBitStringContents] true to not copy bitStringContents
  228. *
  229. * @return the a copy of the asn1 object.
  230. */
  231. asn1.copy = function(obj, options) {
  232. var copy;
  233. if(forge.util.isArray(obj)) {
  234. copy = [];
  235. for(var i = 0; i < obj.length; ++i) {
  236. copy.push(asn1.copy(obj[i], options));
  237. }
  238. return copy;
  239. }
  240. if(typeof obj === 'string') {
  241. // TODO: copy byte buffer if it's a buffer not a string
  242. return obj;
  243. }
  244. copy = {
  245. tagClass: obj.tagClass,
  246. type: obj.type,
  247. constructed: obj.constructed,
  248. composed: obj.composed,
  249. value: asn1.copy(obj.value, options)
  250. };
  251. if(options && !options.excludeBitStringContents) {
  252. // TODO: copy byte buffer if it's a buffer not a string
  253. copy.bitStringContents = obj.bitStringContents;
  254. }
  255. return copy;
  256. };
  257. /**
  258. * Compares asn1 objects for equality.
  259. *
  260. * Note this function does not run in constant time.
  261. *
  262. * @param obj1 the first asn1 object.
  263. * @param obj2 the second asn1 object.
  264. * @param [options] compare options:
  265. * [includeBitStringContents] true to compare bitStringContents
  266. *
  267. * @return true if the asn1 objects are equal.
  268. */
  269. asn1.equals = function(obj1, obj2, options) {
  270. if(forge.util.isArray(obj1)) {
  271. if(!forge.util.isArray(obj2)) {
  272. return false;
  273. }
  274. if(obj1.length !== obj2.length) {
  275. return false;
  276. }
  277. for(var i = 0; i < obj1.length; ++i) {
  278. if(!asn1.equals(obj1[i], obj2[i])) {
  279. return false;
  280. }
  281. }
  282. return true;
  283. }
  284. if(typeof obj1 !== typeof obj2) {
  285. return false;
  286. }
  287. if(typeof obj1 === 'string') {
  288. return obj1 === obj2;
  289. }
  290. var equal = obj1.tagClass === obj2.tagClass &&
  291. obj1.type === obj2.type &&
  292. obj1.constructed === obj2.constructed &&
  293. obj1.composed === obj2.composed &&
  294. asn1.equals(obj1.value, obj2.value);
  295. if(options && options.includeBitStringContents) {
  296. equal = equal && (obj1.bitStringContents === obj2.bitStringContents);
  297. }
  298. return equal;
  299. };
  300. /**
  301. * Gets the length of a BER-encoded ASN.1 value.
  302. *
  303. * In case the length is not specified, undefined is returned.
  304. *
  305. * @param b the BER-encoded ASN.1 byte buffer, starting with the first
  306. * length byte.
  307. *
  308. * @return the length of the BER-encoded ASN.1 value or undefined.
  309. */
  310. asn1.getBerValueLength = function(b) {
  311. // TODO: move this function and related DER/BER functions to a der.js
  312. // file; better abstract ASN.1 away from der/ber.
  313. var b2 = b.getByte();
  314. if(b2 === 0x80) {
  315. return undefined;
  316. }
  317. // see if the length is "short form" or "long form" (bit 8 set)
  318. var length;
  319. var longForm = b2 & 0x80;
  320. if(!longForm) {
  321. // length is just the first byte
  322. length = b2;
  323. } else {
  324. // the number of bytes the length is specified in bits 7 through 1
  325. // and each length byte is in big-endian base-256
  326. length = b.getInt((b2 & 0x7F) << 3);
  327. }
  328. return length;
  329. };
  330. /**
  331. * Check if the byte buffer has enough bytes. Throws an Error if not.
  332. *
  333. * @param bytes the byte buffer to parse from.
  334. * @param remaining the bytes remaining in the current parsing state.
  335. * @param n the number of bytes the buffer must have.
  336. */
  337. function _checkBufferLength(bytes, remaining, n) {
  338. if(n > remaining) {
  339. var error = new Error('Too few bytes to parse DER.');
  340. error.available = bytes.length();
  341. error.remaining = remaining;
  342. error.requested = n;
  343. throw error;
  344. }
  345. }
  346. /**
  347. * Gets the length of a BER-encoded ASN.1 value.
  348. *
  349. * In case the length is not specified, undefined is returned.
  350. *
  351. * @param bytes the byte buffer to parse from.
  352. * @param remaining the bytes remaining in the current parsing state.
  353. *
  354. * @return the length of the BER-encoded ASN.1 value or undefined.
  355. */
  356. var _getValueLength = function(bytes, remaining) {
  357. // TODO: move this function and related DER/BER functions to a der.js
  358. // file; better abstract ASN.1 away from der/ber.
  359. // fromDer already checked that this byte exists
  360. var b2 = bytes.getByte();
  361. remaining--;
  362. if(b2 === 0x80) {
  363. return undefined;
  364. }
  365. // see if the length is "short form" or "long form" (bit 8 set)
  366. var length;
  367. var longForm = b2 & 0x80;
  368. if(!longForm) {
  369. // length is just the first byte
  370. length = b2;
  371. } else {
  372. // the number of bytes the length is specified in bits 7 through 1
  373. // and each length byte is in big-endian base-256
  374. var longFormBytes = b2 & 0x7F;
  375. _checkBufferLength(bytes, remaining, longFormBytes);
  376. length = bytes.getInt(longFormBytes << 3);
  377. }
  378. // FIXME: this will only happen for 32 bit getInt with high bit set
  379. if(length < 0) {
  380. throw new Error('Negative length: ' + length);
  381. }
  382. return length;
  383. };
  384. /**
  385. * Parses an asn1 object from a byte buffer in DER format.
  386. *
  387. * @param bytes the byte buffer to parse from.
  388. * @param [strict] true to be strict when checking value lengths, false to
  389. * allow truncated values (default: true).
  390. * @param [options] object with options or boolean strict flag
  391. * [strict] true to be strict when checking value lengths, false to
  392. * allow truncated values (default: true).
  393. * [parseAllBytes] true to ensure all bytes are parsed
  394. * (default: true)
  395. * [decodeBitStrings] true to attempt to decode the content of
  396. * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that
  397. * without schema support to understand the data context this can
  398. * erroneously decode values that happen to be valid ASN.1. This
  399. * flag will be deprecated or removed as soon as schema support is
  400. * available. (default: true)
  401. *
  402. * @throws Will throw an error for various malformed input conditions.
  403. *
  404. * @return the parsed asn1 object.
  405. */
  406. asn1.fromDer = function(bytes, options) {
  407. if(options === undefined) {
  408. options = {
  409. strict: true,
  410. parseAllBytes: true,
  411. decodeBitStrings: true
  412. };
  413. }
  414. if(typeof options === 'boolean') {
  415. options = {
  416. strict: options,
  417. parseAllBytes: true,
  418. decodeBitStrings: true
  419. };
  420. }
  421. if(!('strict' in options)) {
  422. options.strict = true;
  423. }
  424. if(!('parseAllBytes' in options)) {
  425. options.parseAllBytes = true;
  426. }
  427. if(!('decodeBitStrings' in options)) {
  428. options.decodeBitStrings = true;
  429. }
  430. // wrap in buffer if needed
  431. if(typeof bytes === 'string') {
  432. bytes = forge.util.createBuffer(bytes);
  433. }
  434. var byteCount = bytes.length();
  435. var value = _fromDer(bytes, bytes.length(), 0, options);
  436. if(options.parseAllBytes && bytes.length() !== 0) {
  437. var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');
  438. error.byteCount = byteCount;
  439. error.remaining = bytes.length();
  440. throw error;
  441. }
  442. return value;
  443. };
  444. /**
  445. * Internal function to parse an asn1 object from a byte buffer in DER format.
  446. *
  447. * @param bytes the byte buffer to parse from.
  448. * @param remaining the number of bytes remaining for this chunk.
  449. * @param depth the current parsing depth.
  450. * @param options object with same options as fromDer().
  451. *
  452. * @return the parsed asn1 object.
  453. */
  454. function _fromDer(bytes, remaining, depth, options) {
  455. // temporary storage for consumption calculations
  456. var start;
  457. // minimum length for ASN.1 DER structure is 2
  458. _checkBufferLength(bytes, remaining, 2);
  459. // get the first byte
  460. var b1 = bytes.getByte();
  461. // consumed one byte
  462. remaining--;
  463. // get the tag class
  464. var tagClass = (b1 & 0xC0);
  465. // get the type (bits 1-5)
  466. var type = b1 & 0x1F;
  467. // get the variable value length and adjust remaining bytes
  468. start = bytes.length();
  469. var length = _getValueLength(bytes, remaining);
  470. remaining -= start - bytes.length();
  471. // ensure there are enough bytes to get the value
  472. if(length !== undefined && length > remaining) {
  473. if(options.strict) {
  474. var error = new Error('Too few bytes to read ASN.1 value.');
  475. error.available = bytes.length();
  476. error.remaining = remaining;
  477. error.requested = length;
  478. throw error;
  479. }
  480. // Note: be lenient with truncated values and use remaining state bytes
  481. length = remaining;
  482. }
  483. // value storage
  484. var value;
  485. // possible BIT STRING contents storage
  486. var bitStringContents;
  487. // constructed flag is bit 6 (32 = 0x20) of the first byte
  488. var constructed = ((b1 & 0x20) === 0x20);
  489. if(constructed) {
  490. // parse child asn1 objects from the value
  491. value = [];
  492. if(length === undefined) {
  493. // asn1 object of indefinite length, read until end tag
  494. for(;;) {
  495. _checkBufferLength(bytes, remaining, 2);
  496. if(bytes.bytes(2) === String.fromCharCode(0, 0)) {
  497. bytes.getBytes(2);
  498. remaining -= 2;
  499. break;
  500. }
  501. start = bytes.length();
  502. value.push(_fromDer(bytes, remaining, depth + 1, options));
  503. remaining -= start - bytes.length();
  504. }
  505. } else {
  506. // parsing asn1 object of definite length
  507. while(length > 0) {
  508. start = bytes.length();
  509. value.push(_fromDer(bytes, length, depth + 1, options));
  510. remaining -= start - bytes.length();
  511. length -= start - bytes.length();
  512. }
  513. }
  514. }
  515. // if a BIT STRING, save the contents including padding
  516. if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&
  517. type === asn1.Type.BITSTRING) {
  518. bitStringContents = bytes.bytes(length);
  519. }
  520. // determine if a non-constructed value should be decoded as a composed
  521. // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)
  522. // can be used this way.
  523. if(value === undefined && options.decodeBitStrings &&
  524. tagClass === asn1.Class.UNIVERSAL &&
  525. // FIXME: OCTET STRINGs not yet supported here
  526. // .. other parts of forge expect to decode OCTET STRINGs manually
  527. (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&
  528. length > 1) {
  529. // save read position
  530. var savedRead = bytes.read;
  531. var savedRemaining = remaining;
  532. var unused = 0;
  533. if(type === asn1.Type.BITSTRING) {
  534. /* The first octet gives the number of bits by which the length of the
  535. bit string is less than the next multiple of eight (this is called
  536. the "number of unused bits").
  537. The second and following octets give the value of the bit string
  538. converted to an octet string. */
  539. _checkBufferLength(bytes, remaining, 1);
  540. unused = bytes.getByte();
  541. remaining--;
  542. }
  543. // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs
  544. if(unused === 0) {
  545. try {
  546. // attempt to parse child asn1 object from the value
  547. // (stored in array to signal composed value)
  548. start = bytes.length();
  549. var subOptions = {
  550. // enforce strict mode to avoid parsing ASN.1 from plain data
  551. strict: true,
  552. decodeBitStrings: true
  553. };
  554. var composed = _fromDer(bytes, remaining, depth + 1, subOptions);
  555. var used = start - bytes.length();
  556. remaining -= used;
  557. if(type == asn1.Type.BITSTRING) {
  558. used++;
  559. }
  560. // if the data all decoded and the class indicates UNIVERSAL or
  561. // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object
  562. var tc = composed.tagClass;
  563. if(used === length &&
  564. (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {
  565. value = [composed];
  566. }
  567. } catch(ex) {
  568. }
  569. }
  570. if(value === undefined) {
  571. // restore read position
  572. bytes.read = savedRead;
  573. remaining = savedRemaining;
  574. }
  575. }
  576. if(value === undefined) {
  577. // asn1 not constructed or composed, get raw value
  578. // TODO: do DER to OID conversion and vice-versa in .toDer?
  579. if(length === undefined) {
  580. if(options.strict) {
  581. throw new Error('Non-constructed ASN.1 object of indefinite length.');
  582. }
  583. // be lenient and use remaining state bytes
  584. length = remaining;
  585. }
  586. if(type === asn1.Type.BMPSTRING) {
  587. value = '';
  588. for(; length > 0; length -= 2) {
  589. _checkBufferLength(bytes, remaining, 2);
  590. value += String.fromCharCode(bytes.getInt16());
  591. remaining -= 2;
  592. }
  593. } else {
  594. value = bytes.getBytes(length);
  595. remaining -= length;
  596. }
  597. }
  598. // add BIT STRING contents if available
  599. var asn1Options = bitStringContents === undefined ? null : {
  600. bitStringContents: bitStringContents
  601. };
  602. // create and return asn1 object
  603. return asn1.create(tagClass, type, constructed, value, asn1Options);
  604. }
  605. /**
  606. * Converts the given asn1 object to a buffer of bytes in DER format.
  607. *
  608. * @param asn1 the asn1 object to convert to bytes.
  609. *
  610. * @return the buffer of bytes.
  611. */
  612. asn1.toDer = function(obj) {
  613. var bytes = forge.util.createBuffer();
  614. // build the first byte
  615. var b1 = obj.tagClass | obj.type;
  616. // for storing the ASN.1 value
  617. var value = forge.util.createBuffer();
  618. // use BIT STRING contents if available and data not changed
  619. var useBitStringContents = false;
  620. if('bitStringContents' in obj) {
  621. useBitStringContents = true;
  622. if(obj.original) {
  623. useBitStringContents = asn1.equals(obj, obj.original);
  624. }
  625. }
  626. if(useBitStringContents) {
  627. value.putBytes(obj.bitStringContents);
  628. } else if(obj.composed) {
  629. // if composed, use each child asn1 object's DER bytes as value
  630. // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed
  631. // from other asn1 objects
  632. if(obj.constructed) {
  633. b1 |= 0x20;
  634. } else {
  635. // type is a bit string, add unused bits of 0x00
  636. value.putByte(0x00);
  637. }
  638. // add all of the child DER bytes together
  639. for(var i = 0; i < obj.value.length; ++i) {
  640. if(obj.value[i] !== undefined) {
  641. value.putBuffer(asn1.toDer(obj.value[i]));
  642. }
  643. }
  644. } else {
  645. // use asn1.value directly
  646. if(obj.type === asn1.Type.BMPSTRING) {
  647. for(var i = 0; i < obj.value.length; ++i) {
  648. value.putInt16(obj.value.charCodeAt(i));
  649. }
  650. } else {
  651. // ensure integer is minimally-encoded
  652. // TODO: should all leading bytes be stripped vs just one?
  653. // .. ex '00 00 01' => '01'?
  654. if(obj.type === asn1.Type.INTEGER &&
  655. obj.value.length > 1 &&
  656. // leading 0x00 for positive integer
  657. ((obj.value.charCodeAt(0) === 0 &&
  658. (obj.value.charCodeAt(1) & 0x80) === 0) ||
  659. // leading 0xFF for negative integer
  660. (obj.value.charCodeAt(0) === 0xFF &&
  661. (obj.value.charCodeAt(1) & 0x80) === 0x80))) {
  662. value.putBytes(obj.value.substr(1));
  663. } else {
  664. value.putBytes(obj.value);
  665. }
  666. }
  667. }
  668. // add tag byte
  669. bytes.putByte(b1);
  670. // use "short form" encoding
  671. if(value.length() <= 127) {
  672. // one byte describes the length
  673. // bit 8 = 0 and bits 7-1 = length
  674. bytes.putByte(value.length() & 0x7F);
  675. } else {
  676. // use "long form" encoding
  677. // 2 to 127 bytes describe the length
  678. // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes
  679. // other bytes: length in base 256, big-endian
  680. var len = value.length();
  681. var lenBytes = '';
  682. do {
  683. lenBytes += String.fromCharCode(len & 0xFF);
  684. len = len >>> 8;
  685. } while(len > 0);
  686. // set first byte to # bytes used to store the length and turn on
  687. // bit 8 to indicate long-form length is used
  688. bytes.putByte(lenBytes.length | 0x80);
  689. // concatenate length bytes in reverse since they were generated
  690. // little endian and we need big endian
  691. for(var i = lenBytes.length - 1; i >= 0; --i) {
  692. bytes.putByte(lenBytes.charCodeAt(i));
  693. }
  694. }
  695. // concatenate value bytes
  696. bytes.putBuffer(value);
  697. return bytes;
  698. };
  699. /**
  700. * Converts an OID dot-separated string to a byte buffer. The byte buffer
  701. * contains only the DER-encoded value, not any tag or length bytes.
  702. *
  703. * @param oid the OID dot-separated string.
  704. *
  705. * @return the byte buffer.
  706. */
  707. asn1.oidToDer = function(oid) {
  708. // split OID into individual values
  709. var values = oid.split('.');
  710. var bytes = forge.util.createBuffer();
  711. // first byte is 40 * value1 + value2
  712. bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));
  713. // other bytes are each value in base 128 with 8th bit set except for
  714. // the last byte for each value
  715. var last, valueBytes, value, b;
  716. for(var i = 2; i < values.length; ++i) {
  717. // produce value bytes in reverse because we don't know how many
  718. // bytes it will take to store the value
  719. last = true;
  720. valueBytes = [];
  721. value = parseInt(values[i], 10);
  722. do {
  723. b = value & 0x7F;
  724. value = value >>> 7;
  725. // if value is not last, then turn on 8th bit
  726. if(!last) {
  727. b |= 0x80;
  728. }
  729. valueBytes.push(b);
  730. last = false;
  731. } while(value > 0);
  732. // add value bytes in reverse (needs to be in big endian)
  733. for(var n = valueBytes.length - 1; n >= 0; --n) {
  734. bytes.putByte(valueBytes[n]);
  735. }
  736. }
  737. return bytes;
  738. };
  739. /**
  740. * Converts a DER-encoded byte buffer to an OID dot-separated string. The
  741. * byte buffer should contain only the DER-encoded value, not any tag or
  742. * length bytes.
  743. *
  744. * @param bytes the byte buffer.
  745. *
  746. * @return the OID dot-separated string.
  747. */
  748. asn1.derToOid = function(bytes) {
  749. var oid;
  750. // wrap in buffer if needed
  751. if(typeof bytes === 'string') {
  752. bytes = forge.util.createBuffer(bytes);
  753. }
  754. // first byte is 40 * value1 + value2
  755. var b = bytes.getByte();
  756. oid = Math.floor(b / 40) + '.' + (b % 40);
  757. // other bytes are each value in base 128 with 8th bit set except for
  758. // the last byte for each value
  759. var value = 0;
  760. while(bytes.length() > 0) {
  761. b = bytes.getByte();
  762. value = value << 7;
  763. // not the last byte for the value
  764. if(b & 0x80) {
  765. value += b & 0x7F;
  766. } else {
  767. // last byte
  768. oid += '.' + (value + b);
  769. value = 0;
  770. }
  771. }
  772. return oid;
  773. };
  774. /**
  775. * Converts a UTCTime value to a date.
  776. *
  777. * Note: GeneralizedTime has 4 digits for the year and is used for X.509
  778. * dates past 2049. Parsing that structure hasn't been implemented yet.
  779. *
  780. * @param utc the UTCTime value to convert.
  781. *
  782. * @return the date.
  783. */
  784. asn1.utcTimeToDate = function(utc) {
  785. /* The following formats can be used:
  786. YYMMDDhhmmZ
  787. YYMMDDhhmm+hh'mm'
  788. YYMMDDhhmm-hh'mm'
  789. YYMMDDhhmmssZ
  790. YYMMDDhhmmss+hh'mm'
  791. YYMMDDhhmmss-hh'mm'
  792. Where:
  793. YY is the least significant two digits of the year
  794. MM is the month (01 to 12)
  795. DD is the day (01 to 31)
  796. hh is the hour (00 to 23)
  797. mm are the minutes (00 to 59)
  798. ss are the seconds (00 to 59)
  799. Z indicates that local time is GMT, + indicates that local time is
  800. later than GMT, and - indicates that local time is earlier than GMT
  801. hh' is the absolute value of the offset from GMT in hours
  802. mm' is the absolute value of the offset from GMT in minutes */
  803. var date = new Date();
  804. // if YY >= 50 use 19xx, if YY < 50 use 20xx
  805. var year = parseInt(utc.substr(0, 2), 10);
  806. year = (year >= 50) ? 1900 + year : 2000 + year;
  807. var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month
  808. var DD = parseInt(utc.substr(4, 2), 10);
  809. var hh = parseInt(utc.substr(6, 2), 10);
  810. var mm = parseInt(utc.substr(8, 2), 10);
  811. var ss = 0;
  812. // not just YYMMDDhhmmZ
  813. if(utc.length > 11) {
  814. // get character after minutes
  815. var c = utc.charAt(10);
  816. var end = 10;
  817. // see if seconds are present
  818. if(c !== '+' && c !== '-') {
  819. // get seconds
  820. ss = parseInt(utc.substr(10, 2), 10);
  821. end += 2;
  822. }
  823. }
  824. // update date
  825. date.setUTCFullYear(year, MM, DD);
  826. date.setUTCHours(hh, mm, ss, 0);
  827. if(end) {
  828. // get +/- after end of time
  829. c = utc.charAt(end);
  830. if(c === '+' || c === '-') {
  831. // get hours+minutes offset
  832. var hhoffset = parseInt(utc.substr(end + 1, 2), 10);
  833. var mmoffset = parseInt(utc.substr(end + 4, 2), 10);
  834. // calculate offset in milliseconds
  835. var offset = hhoffset * 60 + mmoffset;
  836. offset *= 60000;
  837. // apply offset
  838. if(c === '+') {
  839. date.setTime(+date - offset);
  840. } else {
  841. date.setTime(+date + offset);
  842. }
  843. }
  844. }
  845. return date;
  846. };
  847. /**
  848. * Converts a GeneralizedTime value to a date.
  849. *
  850. * @param gentime the GeneralizedTime value to convert.
  851. *
  852. * @return the date.
  853. */
  854. asn1.generalizedTimeToDate = function(gentime) {
  855. /* The following formats can be used:
  856. YYYYMMDDHHMMSS
  857. YYYYMMDDHHMMSS.fff
  858. YYYYMMDDHHMMSSZ
  859. YYYYMMDDHHMMSS.fffZ
  860. YYYYMMDDHHMMSS+hh'mm'
  861. YYYYMMDDHHMMSS.fff+hh'mm'
  862. YYYYMMDDHHMMSS-hh'mm'
  863. YYYYMMDDHHMMSS.fff-hh'mm'
  864. Where:
  865. YYYY is the year
  866. MM is the month (01 to 12)
  867. DD is the day (01 to 31)
  868. hh is the hour (00 to 23)
  869. mm are the minutes (00 to 59)
  870. ss are the seconds (00 to 59)
  871. .fff is the second fraction, accurate to three decimal places
  872. Z indicates that local time is GMT, + indicates that local time is
  873. later than GMT, and - indicates that local time is earlier than GMT
  874. hh' is the absolute value of the offset from GMT in hours
  875. mm' is the absolute value of the offset from GMT in minutes */
  876. var date = new Date();
  877. var YYYY = parseInt(gentime.substr(0, 4), 10);
  878. var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month
  879. var DD = parseInt(gentime.substr(6, 2), 10);
  880. var hh = parseInt(gentime.substr(8, 2), 10);
  881. var mm = parseInt(gentime.substr(10, 2), 10);
  882. var ss = parseInt(gentime.substr(12, 2), 10);
  883. var fff = 0;
  884. var offset = 0;
  885. var isUTC = false;
  886. if(gentime.charAt(gentime.length - 1) === 'Z') {
  887. isUTC = true;
  888. }
  889. var end = gentime.length - 5, c = gentime.charAt(end);
  890. if(c === '+' || c === '-') {
  891. // get hours+minutes offset
  892. var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);
  893. var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);
  894. // calculate offset in milliseconds
  895. offset = hhoffset * 60 + mmoffset;
  896. offset *= 60000;
  897. // apply offset
  898. if(c === '+') {
  899. offset *= -1;
  900. }
  901. isUTC = true;
  902. }
  903. // check for second fraction
  904. if(gentime.charAt(14) === '.') {
  905. fff = parseFloat(gentime.substr(14), 10) * 1000;
  906. }
  907. if(isUTC) {
  908. date.setUTCFullYear(YYYY, MM, DD);
  909. date.setUTCHours(hh, mm, ss, fff);
  910. // apply offset
  911. date.setTime(+date + offset);
  912. } else {
  913. date.setFullYear(YYYY, MM, DD);
  914. date.setHours(hh, mm, ss, fff);
  915. }
  916. return date;
  917. };
  918. /**
  919. * Converts a date to a UTCTime value.
  920. *
  921. * Note: GeneralizedTime has 4 digits for the year and is used for X.509
  922. * dates past 2049. Converting to a GeneralizedTime hasn't been
  923. * implemented yet.
  924. *
  925. * @param date the date to convert.
  926. *
  927. * @return the UTCTime value.
  928. */
  929. asn1.dateToUtcTime = function(date) {
  930. // TODO: validate; currently assumes proper format
  931. if(typeof date === 'string') {
  932. return date;
  933. }
  934. var rval = '';
  935. // create format YYMMDDhhmmssZ
  936. var format = [];
  937. format.push(('' + date.getUTCFullYear()).substr(2));
  938. format.push('' + (date.getUTCMonth() + 1));
  939. format.push('' + date.getUTCDate());
  940. format.push('' + date.getUTCHours());
  941. format.push('' + date.getUTCMinutes());
  942. format.push('' + date.getUTCSeconds());
  943. // ensure 2 digits are used for each format entry
  944. for(var i = 0; i < format.length; ++i) {
  945. if(format[i].length < 2) {
  946. rval += '0';
  947. }
  948. rval += format[i];
  949. }
  950. rval += 'Z';
  951. return rval;
  952. };
  953. /**
  954. * Converts a date to a GeneralizedTime value.
  955. *
  956. * @param date the date to convert.
  957. *
  958. * @return the GeneralizedTime value as a string.
  959. */
  960. asn1.dateToGeneralizedTime = function(date) {
  961. // TODO: validate; currently assumes proper format
  962. if(typeof date === 'string') {
  963. return date;
  964. }
  965. var rval = '';
  966. // create format YYYYMMDDHHMMSSZ
  967. var format = [];
  968. format.push('' + date.getUTCFullYear());
  969. format.push('' + (date.getUTCMonth() + 1));
  970. format.push('' + date.getUTCDate());
  971. format.push('' + date.getUTCHours());
  972. format.push('' + date.getUTCMinutes());
  973. format.push('' + date.getUTCSeconds());
  974. // ensure 2 digits are used for each format entry
  975. for(var i = 0; i < format.length; ++i) {
  976. if(format[i].length < 2) {
  977. rval += '0';
  978. }
  979. rval += format[i];
  980. }
  981. rval += 'Z';
  982. return rval;
  983. };
  984. /**
  985. * Converts a javascript integer to a DER-encoded byte buffer to be used
  986. * as the value for an INTEGER type.
  987. *
  988. * @param x the integer.
  989. *
  990. * @return the byte buffer.
  991. */
  992. asn1.integerToDer = function(x) {
  993. var rval = forge.util.createBuffer();
  994. if(x >= -0x80 && x < 0x80) {
  995. return rval.putSignedInt(x, 8);
  996. }
  997. if(x >= -0x8000 && x < 0x8000) {
  998. return rval.putSignedInt(x, 16);
  999. }
  1000. if(x >= -0x800000 && x < 0x800000) {
  1001. return rval.putSignedInt(x, 24);
  1002. }
  1003. if(x >= -0x80000000 && x < 0x80000000) {
  1004. return rval.putSignedInt(x, 32);
  1005. }
  1006. var error = new Error('Integer too large; max is 32-bits.');
  1007. error.integer = x;
  1008. throw error;
  1009. };
  1010. /**
  1011. * Converts a DER-encoded byte buffer to a javascript integer. This is
  1012. * typically used to decode the value of an INTEGER type.
  1013. *
  1014. * @param bytes the byte buffer.
  1015. *
  1016. * @return the integer.
  1017. */
  1018. asn1.derToInteger = function(bytes) {
  1019. // wrap in buffer if needed
  1020. if(typeof bytes === 'string') {
  1021. bytes = forge.util.createBuffer(bytes);
  1022. }
  1023. var n = bytes.length() * 8;
  1024. if(n > 32) {
  1025. throw new Error('Integer too large; max is 32-bits.');
  1026. }
  1027. return bytes.getSignedInt(n);
  1028. };
  1029. /**
  1030. * Validates that the given ASN.1 object is at least a super set of the
  1031. * given ASN.1 structure. Only tag classes and types are checked. An
  1032. * optional map may also be provided to capture ASN.1 values while the
  1033. * structure is checked.
  1034. *
  1035. * To capture an ASN.1 value, set an object in the validator's 'capture'
  1036. * parameter to the key to use in the capture map. To capture the full
  1037. * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including
  1038. * the leading unused bits counter byte, specify 'captureBitStringContents'.
  1039. * To capture BIT STRING bytes, without the leading unused bits counter byte,
  1040. * specify 'captureBitStringValue'.
  1041. *
  1042. * Objects in the validator may set a field 'optional' to true to indicate
  1043. * that it isn't necessary to pass validation.
  1044. *
  1045. * @param obj the ASN.1 object to validate.
  1046. * @param v the ASN.1 structure validator.
  1047. * @param capture an optional map to capture values in.
  1048. * @param errors an optional array for storing validation errors.
  1049. *
  1050. * @return true on success, false on failure.
  1051. */
  1052. asn1.validate = function(obj, v, capture, errors) {
  1053. var rval = false;
  1054. // ensure tag class and type are the same if specified
  1055. if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&
  1056. (obj.type === v.type || typeof(v.type) === 'undefined')) {
  1057. // ensure constructed flag is the same if specified
  1058. if(obj.constructed === v.constructed ||
  1059. typeof(v.constructed) === 'undefined') {
  1060. rval = true;
  1061. // handle sub values
  1062. if(v.value && forge.util.isArray(v.value)) {
  1063. var j = 0;
  1064. for(var i = 0; rval && i < v.value.length; ++i) {
  1065. rval = v.value[i].optional || false;
  1066. if(obj.value[j]) {
  1067. rval = asn1.validate(obj.value[j], v.value[i], capture, errors);
  1068. if(rval) {
  1069. ++j;
  1070. } else if(v.value[i].optional) {
  1071. rval = true;
  1072. }
  1073. }
  1074. if(!rval && errors) {
  1075. errors.push(
  1076. '[' + v.name + '] ' +
  1077. 'Tag class "' + v.tagClass + '", type "' +
  1078. v.type + '" expected value length "' +
  1079. v.value.length + '", got "' +
  1080. obj.value.length + '"');
  1081. }
  1082. }
  1083. }
  1084. if(rval && capture) {
  1085. if(v.capture) {
  1086. capture[v.capture] = obj.value;
  1087. }
  1088. if(v.captureAsn1) {
  1089. capture[v.captureAsn1] = obj;
  1090. }
  1091. if(v.captureBitStringContents && 'bitStringContents' in obj) {
  1092. capture[v.captureBitStringContents] = obj.bitStringContents;
  1093. }
  1094. if(v.captureBitStringValue && 'bitStringContents' in obj) {
  1095. var value;
  1096. if(obj.bitStringContents.length < 2) {
  1097. capture[v.captureBitStringValue] = '';
  1098. } else {
  1099. // FIXME: support unused bits with data shifting
  1100. var unused = obj.bitStringContents.charCodeAt(0);
  1101. if(unused !== 0) {
  1102. throw new Error(
  1103. 'captureBitStringValue only supported for zero unused bits');
  1104. }
  1105. capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);
  1106. }
  1107. }
  1108. }
  1109. } else if(errors) {
  1110. errors.push(
  1111. '[' + v.name + '] ' +
  1112. 'Expected constructed "' + v.constructed + '", got "' +
  1113. obj.constructed + '"');
  1114. }
  1115. } else if(errors) {
  1116. if(obj.tagClass !== v.tagClass) {
  1117. errors.push(
  1118. '[' + v.name + '] ' +
  1119. 'Expected tag class "' + v.tagClass + '", got "' +
  1120. obj.tagClass + '"');
  1121. }
  1122. if(obj.type !== v.type) {
  1123. errors.push(
  1124. '[' + v.name + '] ' +
  1125. 'Expected type "' + v.type + '", got "' + obj.type + '"');
  1126. }
  1127. }
  1128. return rval;
  1129. };
  1130. // regex for testing for non-latin characters
  1131. var _nonLatinRegex = /[^\\u0000-\\u00ff]/;
  1132. /**
  1133. * Pretty prints an ASN.1 object to a string.
  1134. *
  1135. * @param obj the object to write out.
  1136. * @param level the level in the tree.
  1137. * @param indentation the indentation to use.
  1138. *
  1139. * @return the string.
  1140. */
  1141. asn1.prettyPrint = function(obj, level, indentation) {
  1142. var rval = '';
  1143. // set default level and indentation
  1144. level = level || 0;
  1145. indentation = indentation || 2;
  1146. // start new line for deep levels
  1147. if(level > 0) {
  1148. rval += '\n';
  1149. }
  1150. // create indent
  1151. var indent = '';
  1152. for(var i = 0; i < level * indentation; ++i) {
  1153. indent += ' ';
  1154. }
  1155. // print class:type
  1156. rval += indent + 'Tag: ';
  1157. switch(obj.tagClass) {
  1158. case asn1.Class.UNIVERSAL:
  1159. rval += 'Universal:';
  1160. break;
  1161. case asn1.Class.APPLICATION:
  1162. rval += 'Application:';
  1163. break;
  1164. case asn1.Class.CONTEXT_SPECIFIC:
  1165. rval += 'Context-Specific:';
  1166. break;
  1167. case asn1.Class.PRIVATE:
  1168. rval += 'Private:';
  1169. break;
  1170. }
  1171. if(obj.tagClass === asn1.Class.UNIVERSAL) {
  1172. rval += obj.type;
  1173. // known types
  1174. switch(obj.type) {
  1175. case asn1.Type.NONE:
  1176. rval += ' (None)';
  1177. break;
  1178. case asn1.Type.BOOLEAN:
  1179. rval += ' (Boolean)';
  1180. break;
  1181. case asn1.Type.INTEGER:
  1182. rval += ' (Integer)';
  1183. break;
  1184. case asn1.Type.BITSTRING:
  1185. rval += ' (Bit string)';
  1186. break;
  1187. case asn1.Type.OCTETSTRING:
  1188. rval += ' (Octet string)';
  1189. break;
  1190. case asn1.Type.NULL:
  1191. rval += ' (Null)';
  1192. break;
  1193. case asn1.Type.OID:
  1194. rval += ' (Object Identifier)';
  1195. break;
  1196. case asn1.Type.ODESC:
  1197. rval += ' (Object Descriptor)';
  1198. break;
  1199. case asn1.Type.EXTERNAL:
  1200. rval += ' (External or Instance of)';
  1201. break;
  1202. case asn1.Type.REAL:
  1203. rval += ' (Real)';
  1204. break;
  1205. case asn1.Type.ENUMERATED:
  1206. rval += ' (Enumerated)';
  1207. break;
  1208. case asn1.Type.EMBEDDED:
  1209. rval += ' (Embedded PDV)';
  1210. break;
  1211. case asn1.Type.UTF8:
  1212. rval += ' (UTF8)';
  1213. break;
  1214. case asn1.Type.ROID:
  1215. rval += ' (Relative Object Identifier)';
  1216. break;
  1217. case asn1.Type.SEQUENCE:
  1218. rval += ' (Sequence)';
  1219. break;
  1220. case asn1.Type.SET:
  1221. rval += ' (Set)';
  1222. break;
  1223. case asn1.Type.PRINTABLESTRING:
  1224. rval += ' (Printable String)';
  1225. break;
  1226. case asn1.Type.IA5String:
  1227. rval += ' (IA5String (ASCII))';
  1228. break;
  1229. case asn1.Type.UTCTIME:
  1230. rval += ' (UTC time)';
  1231. break;
  1232. case asn1.Type.GENERALIZEDTIME:
  1233. rval += ' (Generalized time)';
  1234. break;
  1235. case asn1.Type.BMPSTRING:
  1236. rval += ' (BMP String)';
  1237. break;
  1238. }
  1239. } else {
  1240. rval += obj.type;
  1241. }
  1242. rval += '\n';
  1243. rval += indent + 'Constructed: ' + obj.constructed + '\n';
  1244. if(obj.composed) {
  1245. var subvalues = 0;
  1246. var sub = '';
  1247. for(var i = 0; i < obj.value.length; ++i) {
  1248. if(obj.value[i] !== undefined) {
  1249. subvalues += 1;
  1250. sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);
  1251. if((i + 1) < obj.value.length) {
  1252. sub += ',';
  1253. }
  1254. }
  1255. }
  1256. rval += indent + 'Sub values: ' + subvalues + sub;
  1257. } else {
  1258. rval += indent + 'Value: ';
  1259. if(obj.type === asn1.Type.OID) {
  1260. var oid = asn1.derToOid(obj.value);
  1261. rval += oid;
  1262. if(forge.pki && forge.pki.oids) {
  1263. if(oid in forge.pki.oids) {
  1264. rval += ' (' + forge.pki.oids[oid] + ') ';
  1265. }
  1266. }
  1267. }
  1268. if(obj.type === asn1.Type.INTEGER) {
  1269. try {
  1270. rval += asn1.derToInteger(obj.value);
  1271. } catch(ex) {
  1272. rval += '0x' + forge.util.bytesToHex(obj.value);
  1273. }
  1274. } else if(obj.type === asn1.Type.BITSTRING) {
  1275. // TODO: shift bits as needed to display without padding
  1276. if(obj.value.length > 1) {
  1277. // remove unused bits field
  1278. rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));
  1279. } else {
  1280. rval += '(none)';
  1281. }
  1282. // show unused bit count
  1283. if(obj.value.length > 0) {
  1284. var unused = obj.value.charCodeAt(0);
  1285. if(unused == 1) {
  1286. rval += ' (1 unused bit shown)';
  1287. } else if(unused > 1) {
  1288. rval += ' (' + unused + ' unused bits shown)';
  1289. }
  1290. }
  1291. } else if(obj.type === asn1.Type.OCTETSTRING) {
  1292. if(!_nonLatinRegex.test(obj.value)) {
  1293. rval += '(' + obj.value + ') ';
  1294. }
  1295. rval += '0x' + forge.util.bytesToHex(obj.value);
  1296. } else if(obj.type === asn1.Type.UTF8) {
  1297. try {
  1298. rval += forge.util.decodeUtf8(obj.value);
  1299. } catch(e) {
  1300. if(e.message === 'URI malformed') {
  1301. rval +=
  1302. '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';
  1303. } else {
  1304. throw e;
  1305. }
  1306. }
  1307. } else if(obj.type === asn1.Type.PRINTABLESTRING ||
  1308. obj.type === asn1.Type.IA5String) {
  1309. rval += obj.value;
  1310. } else if(_nonLatinRegex.test(obj.value)) {
  1311. rval += '0x' + forge.util.bytesToHex(obj.value);
  1312. } else if(obj.value.length === 0) {
  1313. rval += '[null]';
  1314. } else {
  1315. rval += obj.value;
  1316. }
  1317. }
  1318. return rval;
  1319. };