X509Name.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.IO;
  6. using System.Text;
  7. #if SILVERLIGHT || PORTABLE || NETFX_CORE
  8. using System.Collections.Generic;
  9. #endif
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
  13. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
  14. {
  15. /**
  16. * <pre>
  17. * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  18. *
  19. * RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
  20. *
  21. * AttributeTypeAndValue ::= SEQUENCE {
  22. * type OBJECT IDENTIFIER,
  23. * value ANY }
  24. * </pre>
  25. */
  26. public class X509Name
  27. : Asn1Encodable
  28. {
  29. /**
  30. * country code - StringType(SIZE(2))
  31. */
  32. public static readonly DerObjectIdentifier C = new DerObjectIdentifier("2.5.4.6");
  33. /**
  34. * organization - StringType(SIZE(1..64))
  35. */
  36. public static readonly DerObjectIdentifier O = new DerObjectIdentifier("2.5.4.10");
  37. /**
  38. * organizational unit name - StringType(SIZE(1..64))
  39. */
  40. public static readonly DerObjectIdentifier OU = new DerObjectIdentifier("2.5.4.11");
  41. /**
  42. * Title
  43. */
  44. public static readonly DerObjectIdentifier T = new DerObjectIdentifier("2.5.4.12");
  45. /**
  46. * common name - StringType(SIZE(1..64))
  47. */
  48. public static readonly DerObjectIdentifier CN = new DerObjectIdentifier("2.5.4.3");
  49. /**
  50. * street - StringType(SIZE(1..64))
  51. */
  52. public static readonly DerObjectIdentifier Street = new DerObjectIdentifier("2.5.4.9");
  53. /**
  54. * device serial number name - StringType(SIZE(1..64))
  55. */
  56. public static readonly DerObjectIdentifier SerialNumber = new DerObjectIdentifier("2.5.4.5");
  57. /**
  58. * locality name - StringType(SIZE(1..64))
  59. */
  60. public static readonly DerObjectIdentifier L = new DerObjectIdentifier("2.5.4.7");
  61. /**
  62. * state, or province name - StringType(SIZE(1..64))
  63. */
  64. public static readonly DerObjectIdentifier ST = new DerObjectIdentifier("2.5.4.8");
  65. /**
  66. * Naming attributes of type X520name
  67. */
  68. public static readonly DerObjectIdentifier Surname = new DerObjectIdentifier("2.5.4.4");
  69. public static readonly DerObjectIdentifier GivenName = new DerObjectIdentifier("2.5.4.42");
  70. public static readonly DerObjectIdentifier Initials = new DerObjectIdentifier("2.5.4.43");
  71. public static readonly DerObjectIdentifier Generation = new DerObjectIdentifier("2.5.4.44");
  72. public static readonly DerObjectIdentifier UniqueIdentifier = new DerObjectIdentifier("2.5.4.45");
  73. /**
  74. * businessCategory - DirectoryString(SIZE(1..128)
  75. */
  76. public static readonly DerObjectIdentifier BusinessCategory = new DerObjectIdentifier(
  77. "2.5.4.15");
  78. /**
  79. * postalCode - DirectoryString(SIZE(1..40)
  80. */
  81. public static readonly DerObjectIdentifier PostalCode = new DerObjectIdentifier(
  82. "2.5.4.17");
  83. /**
  84. * dnQualifier - DirectoryString(SIZE(1..64)
  85. */
  86. public static readonly DerObjectIdentifier DnQualifier = new DerObjectIdentifier(
  87. "2.5.4.46");
  88. /**
  89. * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64)
  90. */
  91. public static readonly DerObjectIdentifier Pseudonym = new DerObjectIdentifier(
  92. "2.5.4.65");
  93. /**
  94. * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z
  95. */
  96. public static readonly DerObjectIdentifier DateOfBirth = new DerObjectIdentifier(
  97. "1.3.6.1.5.5.7.9.1");
  98. /**
  99. * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128)
  100. */
  101. public static readonly DerObjectIdentifier PlaceOfBirth = new DerObjectIdentifier(
  102. "1.3.6.1.5.5.7.9.2");
  103. /**
  104. * RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f"
  105. */
  106. public static readonly DerObjectIdentifier Gender = new DerObjectIdentifier(
  107. "1.3.6.1.5.5.7.9.3");
  108. /**
  109. * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
  110. * codes only
  111. */
  112. public static readonly DerObjectIdentifier CountryOfCitizenship = new DerObjectIdentifier(
  113. "1.3.6.1.5.5.7.9.4");
  114. /**
  115. * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
  116. * codes only
  117. */
  118. public static readonly DerObjectIdentifier CountryOfResidence = new DerObjectIdentifier(
  119. "1.3.6.1.5.5.7.9.5");
  120. /**
  121. * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64)
  122. */
  123. public static readonly DerObjectIdentifier NameAtBirth = new DerObjectIdentifier("1.3.36.8.3.14");
  124. /**
  125. * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF
  126. * DirectoryString(SIZE(1..30))
  127. */
  128. public static readonly DerObjectIdentifier PostalAddress = new DerObjectIdentifier("2.5.4.16");
  129. /**
  130. * RFC 2256 dmdName
  131. */
  132. public static readonly DerObjectIdentifier DmdName = new DerObjectIdentifier("2.5.4.54");
  133. /**
  134. * id-at-telephoneNumber
  135. */
  136. public static readonly DerObjectIdentifier TelephoneNumber = X509ObjectIdentifiers.id_at_telephoneNumber;
  137. /**
  138. * id-at-organizationIdentifier
  139. */
  140. public static readonly DerObjectIdentifier OrganizationIdentifier = X509ObjectIdentifiers.id_at_organizationIdentifier;
  141. /**
  142. * id-at-name
  143. */
  144. public static readonly DerObjectIdentifier Name = X509ObjectIdentifiers.id_at_name;
  145. /**
  146. * Email address (RSA PKCS#9 extension) - IA5String.
  147. * <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.</p>
  148. */
  149. public static readonly DerObjectIdentifier EmailAddress = PkcsObjectIdentifiers.Pkcs9AtEmailAddress;
  150. /**
  151. * more from PKCS#9
  152. */
  153. public static readonly DerObjectIdentifier UnstructuredName = PkcsObjectIdentifiers.Pkcs9AtUnstructuredName;
  154. public static readonly DerObjectIdentifier UnstructuredAddress = PkcsObjectIdentifiers.Pkcs9AtUnstructuredAddress;
  155. /**
  156. * email address in Verisign certificates
  157. */
  158. public static readonly DerObjectIdentifier E = EmailAddress;
  159. /*
  160. * others...
  161. */
  162. public static readonly DerObjectIdentifier DC = new DerObjectIdentifier("0.9.2342.19200300.100.1.25");
  163. /**
  164. * LDAP User id.
  165. */
  166. public static readonly DerObjectIdentifier UID = new DerObjectIdentifier("0.9.2342.19200300.100.1.1");
  167. /**
  168. * determines whether or not strings should be processed and printed
  169. * from back to front.
  170. */
  171. // public static bool DefaultReverse = false;
  172. public static bool DefaultReverse
  173. {
  174. get { return defaultReverse[0]; }
  175. set { defaultReverse[0] = value; }
  176. }
  177. private static readonly bool[] defaultReverse = { false };
  178. #if SILVERLIGHT || PORTABLE || NETFX_CORE
  179. /**
  180. * default look up table translating OID values into their common symbols following
  181. * the convention in RFC 2253 with a few extras
  182. */
  183. public static readonly IDictionary DefaultSymbols = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
  184. /**
  185. * look up table translating OID values into their common symbols following the convention in RFC 2253
  186. */
  187. public static readonly IDictionary RFC2253Symbols = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
  188. /**
  189. * look up table translating OID values into their common symbols following the convention in RFC 1779
  190. *
  191. */
  192. public static readonly IDictionary RFC1779Symbols = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
  193. /**
  194. * look up table translating common symbols into their OIDS.
  195. */
  196. public static readonly IDictionary DefaultLookup = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
  197. #else
  198. /**
  199. * default look up table translating OID values into their common symbols following
  200. * the convention in RFC 2253 with a few extras
  201. */
  202. public static readonly Hashtable DefaultSymbols = new Hashtable();
  203. /**
  204. * look up table translating OID values into their common symbols following the convention in RFC 2253
  205. */
  206. public static readonly Hashtable RFC2253Symbols = new Hashtable();
  207. /**
  208. * look up table translating OID values into their common symbols following the convention in RFC 1779
  209. *
  210. */
  211. public static readonly Hashtable RFC1779Symbols = new Hashtable();
  212. /**
  213. * look up table translating common symbols into their OIDS.
  214. */
  215. public static readonly Hashtable DefaultLookup = new Hashtable();
  216. #endif
  217. static X509Name()
  218. {
  219. DefaultSymbols.Add(C, "C");
  220. DefaultSymbols.Add(O, "O");
  221. DefaultSymbols.Add(T, "T");
  222. DefaultSymbols.Add(OU, "OU");
  223. DefaultSymbols.Add(CN, "CN");
  224. DefaultSymbols.Add(L, "L");
  225. DefaultSymbols.Add(ST, "ST");
  226. DefaultSymbols.Add(SerialNumber, "SERIALNUMBER");
  227. DefaultSymbols.Add(EmailAddress, "E");
  228. DefaultSymbols.Add(DC, "DC");
  229. DefaultSymbols.Add(UID, "UID");
  230. DefaultSymbols.Add(Street, "STREET");
  231. DefaultSymbols.Add(Surname, "SURNAME");
  232. DefaultSymbols.Add(GivenName, "GIVENNAME");
  233. DefaultSymbols.Add(Initials, "INITIALS");
  234. DefaultSymbols.Add(Generation, "GENERATION");
  235. DefaultSymbols.Add(UnstructuredAddress, "unstructuredAddress");
  236. DefaultSymbols.Add(UnstructuredName, "unstructuredName");
  237. DefaultSymbols.Add(UniqueIdentifier, "UniqueIdentifier");
  238. DefaultSymbols.Add(DnQualifier, "DN");
  239. DefaultSymbols.Add(Pseudonym, "Pseudonym");
  240. DefaultSymbols.Add(PostalAddress, "PostalAddress");
  241. DefaultSymbols.Add(NameAtBirth, "NameAtBirth");
  242. DefaultSymbols.Add(CountryOfCitizenship, "CountryOfCitizenship");
  243. DefaultSymbols.Add(CountryOfResidence, "CountryOfResidence");
  244. DefaultSymbols.Add(Gender, "Gender");
  245. DefaultSymbols.Add(PlaceOfBirth, "PlaceOfBirth");
  246. DefaultSymbols.Add(DateOfBirth, "DateOfBirth");
  247. DefaultSymbols.Add(PostalCode, "PostalCode");
  248. DefaultSymbols.Add(BusinessCategory, "BusinessCategory");
  249. DefaultSymbols.Add(TelephoneNumber, "TelephoneNumber");
  250. RFC2253Symbols.Add(C, "C");
  251. RFC2253Symbols.Add(O, "O");
  252. RFC2253Symbols.Add(OU, "OU");
  253. RFC2253Symbols.Add(CN, "CN");
  254. RFC2253Symbols.Add(L, "L");
  255. RFC2253Symbols.Add(ST, "ST");
  256. RFC2253Symbols.Add(Street, "STREET");
  257. RFC2253Symbols.Add(DC, "DC");
  258. RFC2253Symbols.Add(UID, "UID");
  259. RFC1779Symbols.Add(C, "C");
  260. RFC1779Symbols.Add(O, "O");
  261. RFC1779Symbols.Add(OU, "OU");
  262. RFC1779Symbols.Add(CN, "CN");
  263. RFC1779Symbols.Add(L, "L");
  264. RFC1779Symbols.Add(ST, "ST");
  265. RFC1779Symbols.Add(Street, "STREET");
  266. DefaultLookup.Add("c", C);
  267. DefaultLookup.Add("o", O);
  268. DefaultLookup.Add("t", T);
  269. DefaultLookup.Add("ou", OU);
  270. DefaultLookup.Add("cn", CN);
  271. DefaultLookup.Add("l", L);
  272. DefaultLookup.Add("st", ST);
  273. DefaultLookup.Add("serialnumber", SerialNumber);
  274. DefaultLookup.Add("street", Street);
  275. DefaultLookup.Add("emailaddress", E);
  276. DefaultLookup.Add("dc", DC);
  277. DefaultLookup.Add("e", E);
  278. DefaultLookup.Add("uid", UID);
  279. DefaultLookup.Add("surname", Surname);
  280. DefaultLookup.Add("givenname", GivenName);
  281. DefaultLookup.Add("initials", Initials);
  282. DefaultLookup.Add("generation", Generation);
  283. DefaultLookup.Add("unstructuredaddress", UnstructuredAddress);
  284. DefaultLookup.Add("unstructuredname", UnstructuredName);
  285. DefaultLookup.Add("uniqueidentifier", UniqueIdentifier);
  286. DefaultLookup.Add("dn", DnQualifier);
  287. DefaultLookup.Add("pseudonym", Pseudonym);
  288. DefaultLookup.Add("postaladdress", PostalAddress);
  289. DefaultLookup.Add("nameofbirth", NameAtBirth);
  290. DefaultLookup.Add("countryofcitizenship", CountryOfCitizenship);
  291. DefaultLookup.Add("countryofresidence", CountryOfResidence);
  292. DefaultLookup.Add("gender", Gender);
  293. DefaultLookup.Add("placeofbirth", PlaceOfBirth);
  294. DefaultLookup.Add("dateofbirth", DateOfBirth);
  295. DefaultLookup.Add("postalcode", PostalCode);
  296. DefaultLookup.Add("businesscategory", BusinessCategory);
  297. DefaultLookup.Add("telephonenumber", TelephoneNumber);
  298. }
  299. private readonly IList ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  300. private readonly X509NameEntryConverter converter;
  301. private IList values = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  302. private IList added = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  303. private Asn1Sequence seq;
  304. /**
  305. * Return a X509Name based on the passed in tagged object.
  306. *
  307. * @param obj tag object holding name.
  308. * @param explicitly true if explicitly tagged false otherwise.
  309. * @return the X509Name
  310. */
  311. public static X509Name GetInstance(
  312. Asn1TaggedObject obj,
  313. bool explicitly)
  314. {
  315. return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
  316. }
  317. public static X509Name GetInstance(
  318. object obj)
  319. {
  320. if (obj is X509Name)
  321. return (X509Name)obj;
  322. if (obj == null)
  323. return null;
  324. return new X509Name(Asn1Sequence.GetInstance(obj));
  325. }
  326. protected X509Name()
  327. {
  328. }
  329. /**
  330. * Constructor from Asn1Sequence
  331. *
  332. * the principal will be a list of constructed sets, each containing an (OID, string) pair.
  333. */
  334. protected X509Name(
  335. Asn1Sequence seq)
  336. {
  337. this.seq = seq;
  338. foreach (Asn1Encodable asn1Obj in seq)
  339. {
  340. Asn1Set asn1Set = Asn1Set.GetInstance(asn1Obj.ToAsn1Object());
  341. for (int i = 0; i < asn1Set.Count; i++)
  342. {
  343. Asn1Sequence s = Asn1Sequence.GetInstance(asn1Set[i].ToAsn1Object());
  344. if (s.Count != 2)
  345. throw new ArgumentException("badly sized pair");
  346. ordering.Add(DerObjectIdentifier.GetInstance(s[0].ToAsn1Object()));
  347. Asn1Object derValue = s[1].ToAsn1Object();
  348. if (derValue is IAsn1String && !(derValue is DerUniversalString))
  349. {
  350. string v = ((IAsn1String)derValue).GetString();
  351. if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(v, "#"))
  352. {
  353. v = "\\" + v;
  354. }
  355. values.Add(v);
  356. }
  357. else
  358. {
  359. values.Add("#" + Hex.ToHexString(derValue.GetEncoded()));
  360. }
  361. added.Add(i != 0);
  362. }
  363. }
  364. }
  365. /**
  366. * Constructor from a table of attributes with ordering.
  367. * <p>
  368. * it's is assumed the table contains OID/string pairs, and the contents
  369. * of the table are copied into an internal table as part of the
  370. * construction process. The ordering ArrayList should contain the OIDs
  371. * in the order they are meant to be encoded or printed in ToString.</p>
  372. */
  373. public X509Name(
  374. IList ordering,
  375. IDictionary attributes)
  376. : this(ordering, attributes, new X509DefaultEntryConverter())
  377. {
  378. }
  379. /**
  380. * Constructor from a table of attributes with ordering.
  381. * <p>
  382. * it's is assumed the table contains OID/string pairs, and the contents
  383. * of the table are copied into an internal table as part of the
  384. * construction process. The ordering ArrayList should contain the OIDs
  385. * in the order they are meant to be encoded or printed in ToString.</p>
  386. * <p>
  387. * The passed in converter will be used to convert the strings into their
  388. * ASN.1 counterparts.</p>
  389. */
  390. public X509Name(
  391. IList ordering,
  392. IDictionary attributes,
  393. X509NameEntryConverter converter)
  394. {
  395. this.converter = converter;
  396. foreach (DerObjectIdentifier oid in ordering)
  397. {
  398. object attribute = attributes[oid];
  399. if (attribute == null)
  400. {
  401. throw new ArgumentException("No attribute for object id - " + oid + " - passed to distinguished name");
  402. }
  403. this.ordering.Add(oid);
  404. this.added.Add(false);
  405. this.values.Add(attribute); // copy the hash table
  406. }
  407. }
  408. /**
  409. * Takes two vectors one of the oids and the other of the values.
  410. */
  411. public X509Name(
  412. IList oids,
  413. IList values)
  414. : this(oids, values, new X509DefaultEntryConverter())
  415. {
  416. }
  417. /**
  418. * Takes two vectors one of the oids and the other of the values.
  419. * <p>
  420. * The passed in converter will be used to convert the strings into their
  421. * ASN.1 counterparts.</p>
  422. */
  423. public X509Name(
  424. IList oids,
  425. IList values,
  426. X509NameEntryConverter converter)
  427. {
  428. this.converter = converter;
  429. if (oids.Count != values.Count)
  430. {
  431. throw new ArgumentException("'oids' must be same length as 'values'.");
  432. }
  433. for (int i = 0; i < oids.Count; i++)
  434. {
  435. this.ordering.Add(oids[i]);
  436. this.values.Add(values[i]);
  437. this.added.Add(false);
  438. }
  439. }
  440. /**
  441. * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
  442. * some such, converting it into an ordered set of name attributes.
  443. */
  444. public X509Name(
  445. string dirName)
  446. : this(DefaultReverse, (IDictionary)DefaultLookup, dirName)
  447. {
  448. }
  449. /**
  450. * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
  451. * some such, converting it into an ordered set of name attributes with each
  452. * string value being converted to its associated ASN.1 type using the passed
  453. * in converter.
  454. */
  455. public X509Name(
  456. string dirName,
  457. X509NameEntryConverter converter)
  458. : this(DefaultReverse, DefaultLookup, dirName, converter)
  459. {
  460. }
  461. /**
  462. * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
  463. * some such, converting it into an ordered set of name attributes. If reverse
  464. * is true, create the encoded version of the sequence starting from the
  465. * last element in the string.
  466. */
  467. public X509Name(
  468. bool reverse,
  469. string dirName)
  470. : this(reverse, (IDictionary)DefaultLookup, dirName)
  471. {
  472. }
  473. /**
  474. * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
  475. * some such, converting it into an ordered set of name attributes with each
  476. * string value being converted to its associated ASN.1 type using the passed
  477. * in converter. If reverse is true the ASN.1 sequence representing the DN will
  478. * be built by starting at the end of the string, rather than the start.
  479. */
  480. public X509Name(
  481. bool reverse,
  482. string dirName,
  483. X509NameEntryConverter converter)
  484. : this(reverse, DefaultLookup, dirName, converter)
  485. {
  486. }
  487. /**
  488. * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
  489. * some such, converting it into an ordered set of name attributes. lookUp
  490. * should provide a table of lookups, indexed by lowercase only strings and
  491. * yielding a DerObjectIdentifier, other than that OID. and numeric oids
  492. * will be processed automatically.
  493. * <br/>
  494. * If reverse is true, create the encoded version of the sequence
  495. * starting from the last element in the string.
  496. * @param reverse true if we should start scanning from the end (RFC 2553).
  497. * @param lookUp table of names and their oids.
  498. * @param dirName the X.500 string to be parsed.
  499. */
  500. public X509Name(
  501. bool reverse,
  502. IDictionary lookUp,
  503. string dirName)
  504. : this(reverse, lookUp, dirName, new X509DefaultEntryConverter())
  505. {
  506. }
  507. private DerObjectIdentifier DecodeOid(
  508. string name,
  509. IDictionary lookUp)
  510. {
  511. if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name), "OID."))
  512. {
  513. return new DerObjectIdentifier(name.Substring(4));
  514. }
  515. else if (name[0] >= '0' && name[0] <= '9')
  516. {
  517. return new DerObjectIdentifier(name);
  518. }
  519. DerObjectIdentifier oid = (DerObjectIdentifier)lookUp[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(name)];
  520. if (oid == null)
  521. {
  522. throw new ArgumentException("Unknown object id - " + name + " - passed to distinguished name");
  523. }
  524. return oid;
  525. }
  526. /**
  527. * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
  528. * some such, converting it into an ordered set of name attributes. lookUp
  529. * should provide a table of lookups, indexed by lowercase only strings and
  530. * yielding a DerObjectIdentifier, other than that OID. and numeric oids
  531. * will be processed automatically. The passed in converter is used to convert the
  532. * string values to the right of each equals sign to their ASN.1 counterparts.
  533. * <br/>
  534. * @param reverse true if we should start scanning from the end, false otherwise.
  535. * @param lookUp table of names and oids.
  536. * @param dirName the string dirName
  537. * @param converter the converter to convert string values into their ASN.1 equivalents
  538. */
  539. public X509Name(
  540. bool reverse,
  541. IDictionary lookUp,
  542. string dirName,
  543. X509NameEntryConverter converter)
  544. {
  545. this.converter = converter;
  546. X509NameTokenizer nTok = new X509NameTokenizer(dirName);
  547. while (nTok.HasMoreTokens())
  548. {
  549. string token = nTok.NextToken();
  550. int index = token.IndexOf('=');
  551. if (index == -1)
  552. {
  553. throw new ArgumentException("badly formated directory string");
  554. }
  555. string name = token.Substring(0, index);
  556. string value = token.Substring(index + 1);
  557. DerObjectIdentifier oid = DecodeOid(name, lookUp);
  558. if (value.IndexOf('+') > 0)
  559. {
  560. X509NameTokenizer vTok = new X509NameTokenizer(value, '+');
  561. string v = vTok.NextToken();
  562. this.ordering.Add(oid);
  563. this.values.Add(v);
  564. this.added.Add(false);
  565. while (vTok.HasMoreTokens())
  566. {
  567. string sv = vTok.NextToken();
  568. int ndx = sv.IndexOf('=');
  569. string nm = sv.Substring(0, ndx);
  570. string vl = sv.Substring(ndx + 1);
  571. this.ordering.Add(DecodeOid(nm, lookUp));
  572. this.values.Add(vl);
  573. this.added.Add(true);
  574. }
  575. }
  576. else
  577. {
  578. this.ordering.Add(oid);
  579. this.values.Add(value);
  580. this.added.Add(false);
  581. }
  582. }
  583. if (reverse)
  584. {
  585. // this.ordering.Reverse();
  586. // this.values.Reverse();
  587. // this.added.Reverse();
  588. IList o = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  589. IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  590. IList a = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  591. int count = 1;
  592. for (int i = 0; i < this.ordering.Count; i++)
  593. {
  594. if (!((bool) this.added[i]))
  595. {
  596. count = 0;
  597. }
  598. int index = count++;
  599. o.Insert(index, this.ordering[i]);
  600. v.Insert(index, this.values[i]);
  601. a.Insert(index, this.added[i]);
  602. }
  603. this.ordering = o;
  604. this.values = v;
  605. this.added = a;
  606. }
  607. }
  608. /**
  609. * return an IList of the oids in the name, in the order they were found.
  610. */
  611. public IList GetOidList()
  612. {
  613. return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(ordering);
  614. }
  615. /**
  616. * return an IList of the values found in the name, in the order they
  617. * were found.
  618. */
  619. public IList GetValueList()
  620. {
  621. return GetValueList(null);
  622. }
  623. /**
  624. * return an IList of the values found in the name, in the order they
  625. * were found, with the DN label corresponding to passed in oid.
  626. */
  627. public IList GetValueList(DerObjectIdentifier oid)
  628. {
  629. IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  630. for (int i = 0; i != values.Count; i++)
  631. {
  632. if (null == oid || oid.Equals(ordering[i]))
  633. {
  634. string val = (string)values[i];
  635. if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(val, "\\#"))
  636. {
  637. val = val.Substring(1);
  638. }
  639. v.Add(val);
  640. }
  641. }
  642. return v;
  643. }
  644. public override Asn1Object ToAsn1Object()
  645. {
  646. if (seq == null)
  647. {
  648. Asn1EncodableVector vec = new Asn1EncodableVector();
  649. Asn1EncodableVector sVec = new Asn1EncodableVector();
  650. DerObjectIdentifier lstOid = null;
  651. for (int i = 0; i != ordering.Count; i++)
  652. {
  653. DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
  654. string str = (string)values[i];
  655. if (lstOid == null
  656. || ((bool)this.added[i]))
  657. {
  658. }
  659. else
  660. {
  661. vec.Add(new DerSet(sVec));
  662. sVec = new Asn1EncodableVector();
  663. }
  664. sVec.Add(
  665. new DerSequence(
  666. oid,
  667. converter.GetConvertedValue(oid, str)));
  668. lstOid = oid;
  669. }
  670. vec.Add(new DerSet(sVec));
  671. seq = new DerSequence(vec);
  672. }
  673. return seq;
  674. }
  675. /// <param name="other">The X509Name object to test equivalency against.</param>
  676. /// <param name="inOrder">If true, the order of elements must be the same,
  677. /// as well as the values associated with each element.</param>
  678. public bool Equivalent(
  679. X509Name other,
  680. bool inOrder)
  681. {
  682. if (!inOrder)
  683. return this.Equivalent(other);
  684. if (other == null)
  685. return false;
  686. if (other == this)
  687. return true;
  688. int orderingSize = ordering.Count;
  689. if (orderingSize != other.ordering.Count)
  690. return false;
  691. for (int i = 0; i < orderingSize; i++)
  692. {
  693. DerObjectIdentifier oid = (DerObjectIdentifier) ordering[i];
  694. DerObjectIdentifier oOid = (DerObjectIdentifier) other.ordering[i];
  695. if (!oid.Equals(oOid))
  696. return false;
  697. string val = (string) values[i];
  698. string oVal = (string) other.values[i];
  699. if (!equivalentStrings(val, oVal))
  700. return false;
  701. }
  702. return true;
  703. }
  704. /**
  705. * test for equivalence - note: case is ignored.
  706. */
  707. public bool Equivalent(
  708. X509Name other)
  709. {
  710. if (other == null)
  711. return false;
  712. if (other == this)
  713. return true;
  714. int orderingSize = ordering.Count;
  715. if (orderingSize != other.ordering.Count)
  716. {
  717. return false;
  718. }
  719. bool[] indexes = new bool[orderingSize];
  720. int start, end, delta;
  721. if (ordering[0].Equals(other.ordering[0])) // guess forward
  722. {
  723. start = 0;
  724. end = orderingSize;
  725. delta = 1;
  726. }
  727. else // guess reversed - most common problem
  728. {
  729. start = orderingSize - 1;
  730. end = -1;
  731. delta = -1;
  732. }
  733. for (int i = start; i != end; i += delta)
  734. {
  735. bool found = false;
  736. DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
  737. string value = (string)values[i];
  738. for (int j = 0; j < orderingSize; j++)
  739. {
  740. if (indexes[j])
  741. {
  742. continue;
  743. }
  744. DerObjectIdentifier oOid = (DerObjectIdentifier)other.ordering[j];
  745. if (oid.Equals(oOid))
  746. {
  747. string oValue = (string)other.values[j];
  748. if (equivalentStrings(value, oValue))
  749. {
  750. indexes[j] = true;
  751. found = true;
  752. break;
  753. }
  754. }
  755. }
  756. if (!found)
  757. {
  758. return false;
  759. }
  760. }
  761. return true;
  762. }
  763. private static bool equivalentStrings(
  764. string s1,
  765. string s2)
  766. {
  767. string v1 = canonicalize(s1);
  768. string v2 = canonicalize(s2);
  769. if (!v1.Equals(v2))
  770. {
  771. v1 = stripInternalSpaces(v1);
  772. v2 = stripInternalSpaces(v2);
  773. if (!v1.Equals(v2))
  774. {
  775. return false;
  776. }
  777. }
  778. return true;
  779. }
  780. private static string canonicalize(
  781. string s)
  782. {
  783. string v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(s).Trim();
  784. if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(v, "#"))
  785. {
  786. Asn1Object obj = decodeObject(v);
  787. if (obj is IAsn1String)
  788. {
  789. v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(((IAsn1String)obj).GetString()).Trim();
  790. }
  791. }
  792. return v;
  793. }
  794. private static Asn1Object decodeObject(
  795. string v)
  796. {
  797. try
  798. {
  799. return Asn1Object.FromByteArray(Hex.DecodeStrict(v, 1, v.Length - 1));
  800. }
  801. catch (IOException e)
  802. {
  803. throw new InvalidOperationException("unknown encoding in name: " + e.Message, e);
  804. }
  805. }
  806. private static string stripInternalSpaces(
  807. string str)
  808. {
  809. StringBuilder res = new StringBuilder();
  810. if (str.Length != 0)
  811. {
  812. char c1 = str[0];
  813. res.Append(c1);
  814. for (int k = 1; k < str.Length; k++)
  815. {
  816. char c2 = str[k];
  817. if (!(c1 == ' ' && c2 == ' '))
  818. {
  819. res.Append(c2);
  820. }
  821. c1 = c2;
  822. }
  823. }
  824. return res.ToString();
  825. }
  826. private void AppendValue(
  827. StringBuilder buf,
  828. IDictionary oidSymbols,
  829. DerObjectIdentifier oid,
  830. string val)
  831. {
  832. string sym = (string)oidSymbols[oid];
  833. if (sym != null)
  834. {
  835. buf.Append(sym);
  836. }
  837. else
  838. {
  839. buf.Append(oid.Id);
  840. }
  841. buf.Append('=');
  842. int index = buf.Length;
  843. buf.Append(val);
  844. int end = buf.Length;
  845. if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(val, "\\#"))
  846. {
  847. index += 2;
  848. }
  849. while (index != end)
  850. {
  851. if ((buf[index] == ',')
  852. || (buf[index] == '"')
  853. || (buf[index] == '\\')
  854. || (buf[index] == '+')
  855. || (buf[index] == '=')
  856. || (buf[index] == '<')
  857. || (buf[index] == '>')
  858. || (buf[index] == ';'))
  859. {
  860. buf.Insert(index++, "\\");
  861. end++;
  862. }
  863. index++;
  864. }
  865. }
  866. /**
  867. * convert the structure to a string - if reverse is true the
  868. * oids and values are listed out starting with the last element
  869. * in the sequence (ala RFC 2253), otherwise the string will begin
  870. * with the first element of the structure. If no string definition
  871. * for the oid is found in oidSymbols the string value of the oid is
  872. * added. Two standard symbol tables are provided DefaultSymbols, and
  873. * RFC2253Symbols as part of this class.
  874. *
  875. * @param reverse if true start at the end of the sequence and work back.
  876. * @param oidSymbols look up table strings for oids.
  877. */
  878. public string ToString(
  879. bool reverse,
  880. IDictionary oidSymbols)
  881. {
  882. #if SILVERLIGHT || PORTABLE || NETFX_CORE
  883. List<object> components = new List<object>();
  884. #else
  885. ArrayList components = new ArrayList();
  886. #endif
  887. StringBuilder ava = null;
  888. for (int i = 0; i < ordering.Count; i++)
  889. {
  890. if ((bool) added[i])
  891. {
  892. ava.Append('+');
  893. AppendValue(ava, oidSymbols,
  894. (DerObjectIdentifier)ordering[i],
  895. (string)values[i]);
  896. }
  897. else
  898. {
  899. ava = new StringBuilder();
  900. AppendValue(ava, oidSymbols,
  901. (DerObjectIdentifier)ordering[i],
  902. (string)values[i]);
  903. components.Add(ava);
  904. }
  905. }
  906. if (reverse)
  907. {
  908. components.Reverse();
  909. }
  910. StringBuilder buf = new StringBuilder();
  911. if (components.Count > 0)
  912. {
  913. buf.Append(components[0].ToString());
  914. for (int i = 1; i < components.Count; ++i)
  915. {
  916. buf.Append(',');
  917. buf.Append(components[i].ToString());
  918. }
  919. }
  920. return buf.ToString();
  921. }
  922. string cachedStrRepresentation = null;
  923. public override string ToString()
  924. {
  925. return cachedStrRepresentation ?? (cachedStrRepresentation = ToString(DefaultReverse, (IDictionary)DefaultSymbols));
  926. }
  927. }
  928. }
  929. #pragma warning restore
  930. #endif