asn1.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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. * [decodeBitStrings] true to attempt to decode the content of
  394. * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that
  395. * without schema support to understand the data context this can
  396. * erroneously decode values that happen to be valid ASN.1. This
  397. * flag will be deprecated or removed as soon as schema support is
  398. * available. (default: true)
  399. *
  400. * @return the parsed asn1 object.
  401. */
  402. asn1.fromDer = function(bytes, options) {
  403. if(options === undefined) {
  404. options = {
  405. strict: true,
  406. decodeBitStrings: true
  407. };
  408. }
  409. if(typeof options === 'boolean') {
  410. options = {
  411. strict: options,
  412. decodeBitStrings: true
  413. };
  414. }
  415. if(!('strict' in options)) {
  416. options.strict = true;
  417. }
  418. if(!('decodeBitStrings' in options)) {
  419. options.decodeBitStrings = true;
  420. }
  421. // wrap in buffer if needed
  422. if(typeof bytes === 'string') {
  423. bytes = forge.util.createBuffer(bytes);
  424. }
  425. return _fromDer(bytes, bytes.length(), 0, options);
  426. };
  427. /**
  428. * Internal function to parse an asn1 object from a byte buffer in DER format.
  429. *
  430. * @param bytes the byte buffer to parse from.
  431. * @param remaining the number of bytes remaining for this chunk.
  432. * @param depth the current parsing depth.
  433. * @param options object with same options as fromDer().
  434. *
  435. * @return the parsed asn1 object.
  436. */
  437. function _fromDer(bytes, remaining, depth, options) {
  438. // temporary storage for consumption calculations
  439. var start;
  440. // minimum length for ASN.1 DER structure is 2
  441. _checkBufferLength(bytes, remaining, 2);
  442. // get the first byte
  443. var b1 = bytes.getByte();
  444. // consumed one byte
  445. remaining--;
  446. // get the tag class
  447. var tagClass = (b1 & 0xC0);
  448. // get the type (bits 1-5)
  449. var type = b1 & 0x1F;
  450. // get the variable value length and adjust remaining bytes
  451. start = bytes.length();
  452. var length = _getValueLength(bytes, remaining);
  453. remaining -= start - bytes.length();
  454. // ensure there are enough bytes to get the value
  455. if(length !== undefined && length > remaining) {
  456. if(options.strict) {
  457. var error = new Error('Too few bytes to read ASN.1 value.');
  458. error.available = bytes.length();
  459. error.remaining = remaining;
  460. error.requested = length;
  461. throw error;
  462. }
  463. // Note: be lenient with truncated values and use remaining state bytes
  464. length = remaining;
  465. }
  466. // value storage
  467. var value;
  468. // possible BIT STRING contents storage
  469. var bitStringContents;
  470. // constructed flag is bit 6 (32 = 0x20) of the first byte
  471. var constructed = ((b1 & 0x20) === 0x20);
  472. if(constructed) {
  473. // parse child asn1 objects from the value
  474. value = [];
  475. if(length === undefined) {
  476. // asn1 object of indefinite length, read until end tag
  477. for(;;) {
  478. _checkBufferLength(bytes, remaining, 2);
  479. if(bytes.bytes(2) === String.fromCharCode(0, 0)) {
  480. bytes.getBytes(2);
  481. remaining -= 2;
  482. break;
  483. }
  484. start = bytes.length();
  485. value.push(_fromDer(bytes, remaining, depth + 1, options));
  486. remaining -= start - bytes.length();
  487. }
  488. } else {
  489. // parsing asn1 object of definite length
  490. while(length > 0) {
  491. start = bytes.length();
  492. value.push(_fromDer(bytes, length, depth + 1, options));
  493. remaining -= start - bytes.length();
  494. length -= start - bytes.length();
  495. }
  496. }
  497. }
  498. // if a BIT STRING, save the contents including padding
  499. if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&
  500. type === asn1.Type.BITSTRING) {
  501. bitStringContents = bytes.bytes(length);
  502. }
  503. // determine if a non-constructed value should be decoded as a composed
  504. // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)
  505. // can be used this way.
  506. if(value === undefined && options.decodeBitStrings &&
  507. tagClass === asn1.Class.UNIVERSAL &&
  508. // FIXME: OCTET STRINGs not yet supported here
  509. // .. other parts of forge expect to decode OCTET STRINGs manually
  510. (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&
  511. length > 1) {
  512. // save read position
  513. var savedRead = bytes.read;
  514. var savedRemaining = remaining;
  515. var unused = 0;
  516. if(type === asn1.Type.BITSTRING) {
  517. /* The first octet gives the number of bits by which the length of the
  518. bit string is less than the next multiple of eight (this is called
  519. the "number of unused bits").
  520. The second and following octets give the value of the bit string
  521. converted to an octet string. */
  522. _checkBufferLength(bytes, remaining, 1);
  523. unused = bytes.getByte();
  524. remaining--;
  525. }
  526. // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs
  527. if(unused === 0) {
  528. try {
  529. // attempt to parse child asn1 object from the value
  530. // (stored in array to signal composed value)
  531. start = bytes.length();
  532. var subOptions = {
  533. // enforce strict mode to avoid parsing ASN.1 from plain data
  534. verbose: options.verbose,
  535. strict: true,
  536. decodeBitStrings: true
  537. };
  538. var composed = _fromDer(bytes, remaining, depth + 1, subOptions);
  539. var used = start - bytes.length();
  540. remaining -= used;
  541. if(type == asn1.Type.BITSTRING) {
  542. used++;
  543. }
  544. // if the data all decoded and the class indicates UNIVERSAL or
  545. // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object
  546. var tc = composed.tagClass;
  547. if(used === length &&
  548. (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {
  549. value = [composed];
  550. }
  551. } catch(ex) {
  552. }
  553. }
  554. if(value === undefined) {
  555. // restore read position
  556. bytes.read = savedRead;
  557. remaining = savedRemaining;
  558. }
  559. }
  560. if(value === undefined) {
  561. // asn1 not constructed or composed, get raw value
  562. // TODO: do DER to OID conversion and vice-versa in .toDer?
  563. if(length === undefined) {
  564. if(options.strict) {
  565. throw new Error('Non-constructed ASN.1 object of indefinite length.');
  566. }
  567. // be lenient and use remaining state bytes
  568. length = remaining;
  569. }
  570. if(type === asn1.Type.BMPSTRING) {
  571. value = '';
  572. for(; length > 0; length -= 2) {
  573. _checkBufferLength(bytes, remaining, 2);
  574. value += String.fromCharCode(bytes.getInt16());
  575. remaining -= 2;
  576. }
  577. } else {
  578. value = bytes.getBytes(length);
  579. }
  580. }
  581. // add BIT STRING contents if available
  582. var asn1Options = bitStringContents === undefined ? null : {
  583. bitStringContents: bitStringContents
  584. };
  585. // create and return asn1 object
  586. return asn1.create(tagClass, type, constructed, value, asn1Options);
  587. }
  588. /**
  589. * Converts the given asn1 object to a buffer of bytes in DER format.
  590. *
  591. * @param asn1 the asn1 object to convert to bytes.
  592. *
  593. * @return the buffer of bytes.
  594. */
  595. asn1.toDer = function(obj) {
  596. var bytes = forge.util.createBuffer();
  597. // build the first byte
  598. var b1 = obj.tagClass | obj.type;
  599. // for storing the ASN.1 value
  600. var value = forge.util.createBuffer();
  601. // use BIT STRING contents if available and data not changed
  602. var useBitStringContents = false;
  603. if('bitStringContents' in obj) {
  604. useBitStringContents = true;
  605. if(obj.original) {
  606. useBitStringContents = asn1.equals(obj, obj.original);
  607. }
  608. }
  609. if(useBitStringContents) {
  610. value.putBytes(obj.bitStringContents);
  611. } else if(obj.composed) {
  612. // if composed, use each child asn1 object's DER bytes as value
  613. // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed
  614. // from other asn1 objects
  615. if(obj.constructed) {
  616. b1 |= 0x20;
  617. } else {
  618. // type is a bit string, add unused bits of 0x00
  619. value.putByte(0x00);
  620. }
  621. // add all of the child DER bytes together
  622. for(var i = 0; i < obj.value.length; ++i) {
  623. if(obj.value[i] !== undefined) {
  624. value.putBuffer(asn1.toDer(obj.value[i]));
  625. }
  626. }
  627. } else {
  628. // use asn1.value directly
  629. if(obj.type === asn1.Type.BMPSTRING) {
  630. for(var i = 0; i < obj.value.length; ++i) {
  631. value.putInt16(obj.value.charCodeAt(i));
  632. }
  633. } else {
  634. // ensure integer is minimally-encoded
  635. // TODO: should all leading bytes be stripped vs just one?
  636. // .. ex '00 00 01' => '01'?
  637. if(obj.type === asn1.Type.INTEGER &&
  638. obj.value.length > 1 &&
  639. // leading 0x00 for positive integer
  640. ((obj.value.charCodeAt(0) === 0 &&
  641. (obj.value.charCodeAt(1) & 0x80) === 0) ||
  642. // leading 0xFF for negative integer
  643. (obj.value.charCodeAt(0) === 0xFF &&
  644. (obj.value.charCodeAt(1) & 0x80) === 0x80))) {
  645. value.putBytes(obj.value.substr(1));
  646. } else {
  647. value.putBytes(obj.value);
  648. }
  649. }
  650. }
  651. // add tag byte
  652. bytes.putByte(b1);
  653. // use "short form" encoding
  654. if(value.length() <= 127) {
  655. // one byte describes the length
  656. // bit 8 = 0 and bits 7-1 = length
  657. bytes.putByte(value.length() & 0x7F);
  658. } else {
  659. // use "long form" encoding
  660. // 2 to 127 bytes describe the length
  661. // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes
  662. // other bytes: length in base 256, big-endian
  663. var len = value.length();
  664. var lenBytes = '';
  665. do {
  666. lenBytes += String.fromCharCode(len & 0xFF);
  667. len = len >>> 8;
  668. } while(len > 0);
  669. // set first byte to # bytes used to store the length and turn on
  670. // bit 8 to indicate long-form length is used
  671. bytes.putByte(lenBytes.length | 0x80);
  672. // concatenate length bytes in reverse since they were generated
  673. // little endian and we need big endian
  674. for(var i = lenBytes.length - 1; i >= 0; --i) {
  675. bytes.putByte(lenBytes.charCodeAt(i));
  676. }
  677. }
  678. // concatenate value bytes
  679. bytes.putBuffer(value);
  680. return bytes;
  681. };
  682. /**
  683. * Converts an OID dot-separated string to a byte buffer. The byte buffer
  684. * contains only the DER-encoded value, not any tag or length bytes.
  685. *
  686. * @param oid the OID dot-separated string.
  687. *
  688. * @return the byte buffer.
  689. */
  690. asn1.oidToDer = function(oid) {
  691. // split OID into individual values
  692. var values = oid.split('.');
  693. var bytes = forge.util.createBuffer();
  694. // first byte is 40 * value1 + value2
  695. bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));
  696. // other bytes are each value in base 128 with 8th bit set except for
  697. // the last byte for each value
  698. var last, valueBytes, value, b;
  699. for(var i = 2; i < values.length; ++i) {
  700. // produce value bytes in reverse because we don't know how many
  701. // bytes it will take to store the value
  702. last = true;
  703. valueBytes = [];
  704. value = parseInt(values[i], 10);
  705. do {
  706. b = value & 0x7F;
  707. value = value >>> 7;
  708. // if value is not last, then turn on 8th bit
  709. if(!last) {
  710. b |= 0x80;
  711. }
  712. valueBytes.push(b);
  713. last = false;
  714. } while(value > 0);
  715. // add value bytes in reverse (needs to be in big endian)
  716. for(var n = valueBytes.length - 1; n >= 0; --n) {
  717. bytes.putByte(valueBytes[n]);
  718. }
  719. }
  720. return bytes;
  721. };
  722. /**
  723. * Converts a DER-encoded byte buffer to an OID dot-separated string. The
  724. * byte buffer should contain only the DER-encoded value, not any tag or
  725. * length bytes.
  726. *
  727. * @param bytes the byte buffer.
  728. *
  729. * @return the OID dot-separated string.
  730. */
  731. asn1.derToOid = function(bytes) {
  732. var oid;
  733. // wrap in buffer if needed
  734. if(typeof bytes === 'string') {
  735. bytes = forge.util.createBuffer(bytes);
  736. }
  737. // first byte is 40 * value1 + value2
  738. var b = bytes.getByte();
  739. oid = Math.floor(b / 40) + '.' + (b % 40);
  740. // other bytes are each value in base 128 with 8th bit set except for
  741. // the last byte for each value
  742. var value = 0;
  743. while(bytes.length() > 0) {
  744. b = bytes.getByte();
  745. value = value << 7;
  746. // not the last byte for the value
  747. if(b & 0x80) {
  748. value += b & 0x7F;
  749. } else {
  750. // last byte
  751. oid += '.' + (value + b);
  752. value = 0;
  753. }
  754. }
  755. return oid;
  756. };
  757. /**
  758. * Converts a UTCTime value to a date.
  759. *
  760. * Note: GeneralizedTime has 4 digits for the year and is used for X.509
  761. * dates past 2049. Parsing that structure hasn't been implemented yet.
  762. *
  763. * @param utc the UTCTime value to convert.
  764. *
  765. * @return the date.
  766. */
  767. asn1.utcTimeToDate = function(utc) {
  768. /* The following formats can be used:
  769. YYMMDDhhmmZ
  770. YYMMDDhhmm+hh'mm'
  771. YYMMDDhhmm-hh'mm'
  772. YYMMDDhhmmssZ
  773. YYMMDDhhmmss+hh'mm'
  774. YYMMDDhhmmss-hh'mm'
  775. Where:
  776. YY is the least significant two digits of the year
  777. MM is the month (01 to 12)
  778. DD is the day (01 to 31)
  779. hh is the hour (00 to 23)
  780. mm are the minutes (00 to 59)
  781. ss are the seconds (00 to 59)
  782. Z indicates that local time is GMT, + indicates that local time is
  783. later than GMT, and - indicates that local time is earlier than GMT
  784. hh' is the absolute value of the offset from GMT in hours
  785. mm' is the absolute value of the offset from GMT in minutes */
  786. var date = new Date();
  787. // if YY >= 50 use 19xx, if YY < 50 use 20xx
  788. var year = parseInt(utc.substr(0, 2), 10);
  789. year = (year >= 50) ? 1900 + year : 2000 + year;
  790. var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month
  791. var DD = parseInt(utc.substr(4, 2), 10);
  792. var hh = parseInt(utc.substr(6, 2), 10);
  793. var mm = parseInt(utc.substr(8, 2), 10);
  794. var ss = 0;
  795. // not just YYMMDDhhmmZ
  796. if(utc.length > 11) {
  797. // get character after minutes
  798. var c = utc.charAt(10);
  799. var end = 10;
  800. // see if seconds are present
  801. if(c !== '+' && c !== '-') {
  802. // get seconds
  803. ss = parseInt(utc.substr(10, 2), 10);
  804. end += 2;
  805. }
  806. }
  807. // update date
  808. date.setUTCFullYear(year, MM, DD);
  809. date.setUTCHours(hh, mm, ss, 0);
  810. if(end) {
  811. // get +/- after end of time
  812. c = utc.charAt(end);
  813. if(c === '+' || c === '-') {
  814. // get hours+minutes offset
  815. var hhoffset = parseInt(utc.substr(end + 1, 2), 10);
  816. var mmoffset = parseInt(utc.substr(end + 4, 2), 10);
  817. // calculate offset in milliseconds
  818. var offset = hhoffset * 60 + mmoffset;
  819. offset *= 60000;
  820. // apply offset
  821. if(c === '+') {
  822. date.setTime(+date - offset);
  823. } else {
  824. date.setTime(+date + offset);
  825. }
  826. }
  827. }
  828. return date;
  829. };
  830. /**
  831. * Converts a GeneralizedTime value to a date.
  832. *
  833. * @param gentime the GeneralizedTime value to convert.
  834. *
  835. * @return the date.
  836. */
  837. asn1.generalizedTimeToDate = function(gentime) {
  838. /* The following formats can be used:
  839. YYYYMMDDHHMMSS
  840. YYYYMMDDHHMMSS.fff
  841. YYYYMMDDHHMMSSZ
  842. YYYYMMDDHHMMSS.fffZ
  843. YYYYMMDDHHMMSS+hh'mm'
  844. YYYYMMDDHHMMSS.fff+hh'mm'
  845. YYYYMMDDHHMMSS-hh'mm'
  846. YYYYMMDDHHMMSS.fff-hh'mm'
  847. Where:
  848. YYYY is the year
  849. MM is the month (01 to 12)
  850. DD is the day (01 to 31)
  851. hh is the hour (00 to 23)
  852. mm are the minutes (00 to 59)
  853. ss are the seconds (00 to 59)
  854. .fff is the second fraction, accurate to three decimal places
  855. Z indicates that local time is GMT, + indicates that local time is
  856. later than GMT, and - indicates that local time is earlier than GMT
  857. hh' is the absolute value of the offset from GMT in hours
  858. mm' is the absolute value of the offset from GMT in minutes */
  859. var date = new Date();
  860. var YYYY = parseInt(gentime.substr(0, 4), 10);
  861. var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month
  862. var DD = parseInt(gentime.substr(6, 2), 10);
  863. var hh = parseInt(gentime.substr(8, 2), 10);
  864. var mm = parseInt(gentime.substr(10, 2), 10);
  865. var ss = parseInt(gentime.substr(12, 2), 10);
  866. var fff = 0;
  867. var offset = 0;
  868. var isUTC = false;
  869. if(gentime.charAt(gentime.length - 1) === 'Z') {
  870. isUTC = true;
  871. }
  872. var end = gentime.length - 5, c = gentime.charAt(end);
  873. if(c === '+' || c === '-') {
  874. // get hours+minutes offset
  875. var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);
  876. var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);
  877. // calculate offset in milliseconds
  878. offset = hhoffset * 60 + mmoffset;
  879. offset *= 60000;
  880. // apply offset
  881. if(c === '+') {
  882. offset *= -1;
  883. }
  884. isUTC = true;
  885. }
  886. // check for second fraction
  887. if(gentime.charAt(14) === '.') {
  888. fff = parseFloat(gentime.substr(14), 10) * 1000;
  889. }
  890. if(isUTC) {
  891. date.setUTCFullYear(YYYY, MM, DD);
  892. date.setUTCHours(hh, mm, ss, fff);
  893. // apply offset
  894. date.setTime(+date + offset);
  895. } else {
  896. date.setFullYear(YYYY, MM, DD);
  897. date.setHours(hh, mm, ss, fff);
  898. }
  899. return date;
  900. };
  901. /**
  902. * Converts a date to a UTCTime value.
  903. *
  904. * Note: GeneralizedTime has 4 digits for the year and is used for X.509
  905. * dates past 2049. Converting to a GeneralizedTime hasn't been
  906. * implemented yet.
  907. *
  908. * @param date the date to convert.
  909. *
  910. * @return the UTCTime value.
  911. */
  912. asn1.dateToUtcTime = function(date) {
  913. // TODO: validate; currently assumes proper format
  914. if(typeof date === 'string') {
  915. return date;
  916. }
  917. var rval = '';
  918. // create format YYMMDDhhmmssZ
  919. var format = [];
  920. format.push(('' + date.getUTCFullYear()).substr(2));
  921. format.push('' + (date.getUTCMonth() + 1));
  922. format.push('' + date.getUTCDate());
  923. format.push('' + date.getUTCHours());
  924. format.push('' + date.getUTCMinutes());
  925. format.push('' + date.getUTCSeconds());
  926. // ensure 2 digits are used for each format entry
  927. for(var i = 0; i < format.length; ++i) {
  928. if(format[i].length < 2) {
  929. rval += '0';
  930. }
  931. rval += format[i];
  932. }
  933. rval += 'Z';
  934. return rval;
  935. };
  936. /**
  937. * Converts a date to a GeneralizedTime value.
  938. *
  939. * @param date the date to convert.
  940. *
  941. * @return the GeneralizedTime value as a string.
  942. */
  943. asn1.dateToGeneralizedTime = function(date) {
  944. // TODO: validate; currently assumes proper format
  945. if(typeof date === 'string') {
  946. return date;
  947. }
  948. var rval = '';
  949. // create format YYYYMMDDHHMMSSZ
  950. var format = [];
  951. format.push('' + date.getUTCFullYear());
  952. format.push('' + (date.getUTCMonth() + 1));
  953. format.push('' + date.getUTCDate());
  954. format.push('' + date.getUTCHours());
  955. format.push('' + date.getUTCMinutes());
  956. format.push('' + date.getUTCSeconds());
  957. // ensure 2 digits are used for each format entry
  958. for(var i = 0; i < format.length; ++i) {
  959. if(format[i].length < 2) {
  960. rval += '0';
  961. }
  962. rval += format[i];
  963. }
  964. rval += 'Z';
  965. return rval;
  966. };
  967. /**
  968. * Converts a javascript integer to a DER-encoded byte buffer to be used
  969. * as the value for an INTEGER type.
  970. *
  971. * @param x the integer.
  972. *
  973. * @return the byte buffer.
  974. */
  975. asn1.integerToDer = function(x) {
  976. var rval = forge.util.createBuffer();
  977. if(x >= -0x80 && x < 0x80) {
  978. return rval.putSignedInt(x, 8);
  979. }
  980. if(x >= -0x8000 && x < 0x8000) {
  981. return rval.putSignedInt(x, 16);
  982. }
  983. if(x >= -0x800000 && x < 0x800000) {
  984. return rval.putSignedInt(x, 24);
  985. }
  986. if(x >= -0x80000000 && x < 0x80000000) {
  987. return rval.putSignedInt(x, 32);
  988. }
  989. var error = new Error('Integer too large; max is 32-bits.');
  990. error.integer = x;
  991. throw error;
  992. };
  993. /**
  994. * Converts a DER-encoded byte buffer to a javascript integer. This is
  995. * typically used to decode the value of an INTEGER type.
  996. *
  997. * @param bytes the byte buffer.
  998. *
  999. * @return the integer.
  1000. */
  1001. asn1.derToInteger = function(bytes) {
  1002. // wrap in buffer if needed
  1003. if(typeof bytes === 'string') {
  1004. bytes = forge.util.createBuffer(bytes);
  1005. }
  1006. var n = bytes.length() * 8;
  1007. if(n > 32) {
  1008. throw new Error('Integer too large; max is 32-bits.');
  1009. }
  1010. return bytes.getSignedInt(n);
  1011. };
  1012. /**
  1013. * Validates that the given ASN.1 object is at least a super set of the
  1014. * given ASN.1 structure. Only tag classes and types are checked. An
  1015. * optional map may also be provided to capture ASN.1 values while the
  1016. * structure is checked.
  1017. *
  1018. * To capture an ASN.1 value, set an object in the validator's 'capture'
  1019. * parameter to the key to use in the capture map. To capture the full
  1020. * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including
  1021. * the leading unused bits counter byte, specify 'captureBitStringContents'.
  1022. * To capture BIT STRING bytes, without the leading unused bits counter byte,
  1023. * specify 'captureBitStringValue'.
  1024. *
  1025. * Objects in the validator may set a field 'optional' to true to indicate
  1026. * that it isn't necessary to pass validation.
  1027. *
  1028. * @param obj the ASN.1 object to validate.
  1029. * @param v the ASN.1 structure validator.
  1030. * @param capture an optional map to capture values in.
  1031. * @param errors an optional array for storing validation errors.
  1032. *
  1033. * @return true on success, false on failure.
  1034. */
  1035. asn1.validate = function(obj, v, capture, errors) {
  1036. var rval = false;
  1037. // ensure tag class and type are the same if specified
  1038. if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&
  1039. (obj.type === v.type || typeof(v.type) === 'undefined')) {
  1040. // ensure constructed flag is the same if specified
  1041. if(obj.constructed === v.constructed ||
  1042. typeof(v.constructed) === 'undefined') {
  1043. rval = true;
  1044. // handle sub values
  1045. if(v.value && forge.util.isArray(v.value)) {
  1046. var j = 0;
  1047. for(var i = 0; rval && i < v.value.length; ++i) {
  1048. rval = v.value[i].optional || false;
  1049. if(obj.value[j]) {
  1050. rval = asn1.validate(obj.value[j], v.value[i], capture, errors);
  1051. if(rval) {
  1052. ++j;
  1053. } else if(v.value[i].optional) {
  1054. rval = true;
  1055. }
  1056. }
  1057. if(!rval && errors) {
  1058. errors.push(
  1059. '[' + v.name + '] ' +
  1060. 'Tag class "' + v.tagClass + '", type "' +
  1061. v.type + '" expected value length "' +
  1062. v.value.length + '", got "' +
  1063. obj.value.length + '"');
  1064. }
  1065. }
  1066. }
  1067. if(rval && capture) {
  1068. if(v.capture) {
  1069. capture[v.capture] = obj.value;
  1070. }
  1071. if(v.captureAsn1) {
  1072. capture[v.captureAsn1] = obj;
  1073. }
  1074. if(v.captureBitStringContents && 'bitStringContents' in obj) {
  1075. capture[v.captureBitStringContents] = obj.bitStringContents;
  1076. }
  1077. if(v.captureBitStringValue && 'bitStringContents' in obj) {
  1078. var value;
  1079. if(obj.bitStringContents.length < 2) {
  1080. capture[v.captureBitStringValue] = '';
  1081. } else {
  1082. // FIXME: support unused bits with data shifting
  1083. var unused = obj.bitStringContents.charCodeAt(0);
  1084. if(unused !== 0) {
  1085. throw new Error(
  1086. 'captureBitStringValue only supported for zero unused bits');
  1087. }
  1088. capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);
  1089. }
  1090. }
  1091. }
  1092. } else if(errors) {
  1093. errors.push(
  1094. '[' + v.name + '] ' +
  1095. 'Expected constructed "' + v.constructed + '", got "' +
  1096. obj.constructed + '"');
  1097. }
  1098. } else if(errors) {
  1099. if(obj.tagClass !== v.tagClass) {
  1100. errors.push(
  1101. '[' + v.name + '] ' +
  1102. 'Expected tag class "' + v.tagClass + '", got "' +
  1103. obj.tagClass + '"');
  1104. }
  1105. if(obj.type !== v.type) {
  1106. errors.push(
  1107. '[' + v.name + '] ' +
  1108. 'Expected type "' + v.type + '", got "' + obj.type + '"');
  1109. }
  1110. }
  1111. return rval;
  1112. };
  1113. // regex for testing for non-latin characters
  1114. var _nonLatinRegex = /[^\\u0000-\\u00ff]/;
  1115. /**
  1116. * Pretty prints an ASN.1 object to a string.
  1117. *
  1118. * @param obj the object to write out.
  1119. * @param level the level in the tree.
  1120. * @param indentation the indentation to use.
  1121. *
  1122. * @return the string.
  1123. */
  1124. asn1.prettyPrint = function(obj, level, indentation) {
  1125. var rval = '';
  1126. // set default level and indentation
  1127. level = level || 0;
  1128. indentation = indentation || 2;
  1129. // start new line for deep levels
  1130. if(level > 0) {
  1131. rval += '\n';
  1132. }
  1133. // create indent
  1134. var indent = '';
  1135. for(var i = 0; i < level * indentation; ++i) {
  1136. indent += ' ';
  1137. }
  1138. // print class:type
  1139. rval += indent + 'Tag: ';
  1140. switch(obj.tagClass) {
  1141. case asn1.Class.UNIVERSAL:
  1142. rval += 'Universal:';
  1143. break;
  1144. case asn1.Class.APPLICATION:
  1145. rval += 'Application:';
  1146. break;
  1147. case asn1.Class.CONTEXT_SPECIFIC:
  1148. rval += 'Context-Specific:';
  1149. break;
  1150. case asn1.Class.PRIVATE:
  1151. rval += 'Private:';
  1152. break;
  1153. }
  1154. if(obj.tagClass === asn1.Class.UNIVERSAL) {
  1155. rval += obj.type;
  1156. // known types
  1157. switch(obj.type) {
  1158. case asn1.Type.NONE:
  1159. rval += ' (None)';
  1160. break;
  1161. case asn1.Type.BOOLEAN:
  1162. rval += ' (Boolean)';
  1163. break;
  1164. case asn1.Type.INTEGER:
  1165. rval += ' (Integer)';
  1166. break;
  1167. case asn1.Type.BITSTRING:
  1168. rval += ' (Bit string)';
  1169. break;
  1170. case asn1.Type.OCTETSTRING:
  1171. rval += ' (Octet string)';
  1172. break;
  1173. case asn1.Type.NULL:
  1174. rval += ' (Null)';
  1175. break;
  1176. case asn1.Type.OID:
  1177. rval += ' (Object Identifier)';
  1178. break;
  1179. case asn1.Type.ODESC:
  1180. rval += ' (Object Descriptor)';
  1181. break;
  1182. case asn1.Type.EXTERNAL:
  1183. rval += ' (External or Instance of)';
  1184. break;
  1185. case asn1.Type.REAL:
  1186. rval += ' (Real)';
  1187. break;
  1188. case asn1.Type.ENUMERATED:
  1189. rval += ' (Enumerated)';
  1190. break;
  1191. case asn1.Type.EMBEDDED:
  1192. rval += ' (Embedded PDV)';
  1193. break;
  1194. case asn1.Type.UTF8:
  1195. rval += ' (UTF8)';
  1196. break;
  1197. case asn1.Type.ROID:
  1198. rval += ' (Relative Object Identifier)';
  1199. break;
  1200. case asn1.Type.SEQUENCE:
  1201. rval += ' (Sequence)';
  1202. break;
  1203. case asn1.Type.SET:
  1204. rval += ' (Set)';
  1205. break;
  1206. case asn1.Type.PRINTABLESTRING:
  1207. rval += ' (Printable String)';
  1208. break;
  1209. case asn1.Type.IA5String:
  1210. rval += ' (IA5String (ASCII))';
  1211. break;
  1212. case asn1.Type.UTCTIME:
  1213. rval += ' (UTC time)';
  1214. break;
  1215. case asn1.Type.GENERALIZEDTIME:
  1216. rval += ' (Generalized time)';
  1217. break;
  1218. case asn1.Type.BMPSTRING:
  1219. rval += ' (BMP String)';
  1220. break;
  1221. }
  1222. } else {
  1223. rval += obj.type;
  1224. }
  1225. rval += '\n';
  1226. rval += indent + 'Constructed: ' + obj.constructed + '\n';
  1227. if(obj.composed) {
  1228. var subvalues = 0;
  1229. var sub = '';
  1230. for(var i = 0; i < obj.value.length; ++i) {
  1231. if(obj.value[i] !== undefined) {
  1232. subvalues += 1;
  1233. sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);
  1234. if((i + 1) < obj.value.length) {
  1235. sub += ',';
  1236. }
  1237. }
  1238. }
  1239. rval += indent + 'Sub values: ' + subvalues + sub;
  1240. } else {
  1241. rval += indent + 'Value: ';
  1242. if(obj.type === asn1.Type.OID) {
  1243. var oid = asn1.derToOid(obj.value);
  1244. rval += oid;
  1245. if(forge.pki && forge.pki.oids) {
  1246. if(oid in forge.pki.oids) {
  1247. rval += ' (' + forge.pki.oids[oid] + ') ';
  1248. }
  1249. }
  1250. }
  1251. if(obj.type === asn1.Type.INTEGER) {
  1252. try {
  1253. rval += asn1.derToInteger(obj.value);
  1254. } catch(ex) {
  1255. rval += '0x' + forge.util.bytesToHex(obj.value);
  1256. }
  1257. } else if(obj.type === asn1.Type.BITSTRING) {
  1258. // TODO: shift bits as needed to display without padding
  1259. if(obj.value.length > 1) {
  1260. // remove unused bits field
  1261. rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));
  1262. } else {
  1263. rval += '(none)';
  1264. }
  1265. // show unused bit count
  1266. if(obj.value.length > 0) {
  1267. var unused = obj.value.charCodeAt(0);
  1268. if(unused == 1) {
  1269. rval += ' (1 unused bit shown)';
  1270. } else if(unused > 1) {
  1271. rval += ' (' + unused + ' unused bits shown)';
  1272. }
  1273. }
  1274. } else if(obj.type === asn1.Type.OCTETSTRING) {
  1275. if(!_nonLatinRegex.test(obj.value)) {
  1276. rval += '(' + obj.value + ') ';
  1277. }
  1278. rval += '0x' + forge.util.bytesToHex(obj.value);
  1279. } else if(obj.type === asn1.Type.UTF8) {
  1280. rval += forge.util.decodeUtf8(obj.value);
  1281. } else if(obj.type === asn1.Type.PRINTABLESTRING ||
  1282. obj.type === asn1.Type.IA5String) {
  1283. rval += obj.value;
  1284. } else if(_nonLatinRegex.test(obj.value)) {
  1285. rval += '0x' + forge.util.bytesToHex(obj.value);
  1286. } else if(obj.value.length === 0) {
  1287. rval += '[null]';
  1288. } else {
  1289. rval += obj.value;
  1290. }
  1291. }
  1292. return rval;
  1293. };