X509Certificate.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.Collections;
  4. using System.IO;
  5. using System.Text;
  6. using Org.BouncyCastle.Asn1;
  7. using Org.BouncyCastle.Asn1.Misc;
  8. using Org.BouncyCastle.Asn1.Utilities;
  9. using Org.BouncyCastle.Asn1.X509;
  10. using Org.BouncyCastle.Crypto;
  11. using Org.BouncyCastle.Math;
  12. using Org.BouncyCastle.Security;
  13. using Org.BouncyCastle.Security.Certificates;
  14. using Org.BouncyCastle.Utilities;
  15. using Org.BouncyCastle.Utilities.Encoders;
  16. using Org.BouncyCastle.X509.Extension;
  17. using Org.BouncyCastle.Crypto.Operators;
  18. namespace Org.BouncyCastle.X509
  19. {
  20. /// <summary>
  21. /// An Object representing an X509 Certificate.
  22. /// Has static methods for loading Certificates encoded in many forms that return X509Certificate Objects.
  23. /// </summary>
  24. public class X509Certificate
  25. : X509ExtensionBase
  26. // , PKCS12BagAttributeCarrier
  27. {
  28. private readonly X509CertificateStructure c;
  29. // private Hashtable pkcs12Attributes = new Hashtable();
  30. // private ArrayList pkcs12Ordering = new ArrayList();
  31. private readonly BasicConstraints basicConstraints;
  32. private readonly bool[] keyUsage;
  33. private bool hashValueSet;
  34. private int hashValue;
  35. protected X509Certificate()
  36. {
  37. }
  38. public X509Certificate(
  39. X509CertificateStructure c)
  40. {
  41. this.c = c;
  42. try
  43. {
  44. Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
  45. if (str != null)
  46. {
  47. basicConstraints = BasicConstraints.GetInstance(
  48. X509ExtensionUtilities.FromExtensionValue(str));
  49. }
  50. }
  51. catch (Exception e)
  52. {
  53. throw new CertificateParsingException("cannot construct BasicConstraints: " + e);
  54. }
  55. try
  56. {
  57. Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
  58. if (str != null)
  59. {
  60. DerBitString bits = DerBitString.GetInstance(
  61. X509ExtensionUtilities.FromExtensionValue(str));
  62. byte[] bytes = bits.GetBytes();
  63. int length = (bytes.Length * 8) - bits.PadBits;
  64. keyUsage = new bool[(length < 9) ? 9 : length];
  65. for (int i = 0; i != length; i++)
  66. {
  67. // keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
  68. keyUsage[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0;
  69. }
  70. }
  71. else
  72. {
  73. keyUsage = null;
  74. }
  75. }
  76. catch (Exception e)
  77. {
  78. throw new CertificateParsingException("cannot construct KeyUsage: " + e);
  79. }
  80. }
  81. // internal X509Certificate(
  82. // Asn1Sequence seq)
  83. // {
  84. // this.c = X509CertificateStructure.GetInstance(seq);
  85. // }
  86. // /// <summary>
  87. // /// Load certificate from byte array.
  88. // /// </summary>
  89. // /// <param name="encoded">Byte array containing encoded X509Certificate.</param>
  90. // public X509Certificate(
  91. // byte[] encoded)
  92. // : this((Asn1Sequence) new Asn1InputStream(encoded).ReadObject())
  93. // {
  94. // }
  95. //
  96. // /// <summary>
  97. // /// Load certificate from Stream.
  98. // /// Must be positioned at start of certificate.
  99. // /// </summary>
  100. // /// <param name="input"></param>
  101. // public X509Certificate(
  102. // Stream input)
  103. // : this((Asn1Sequence) new Asn1InputStream(input).ReadObject())
  104. // {
  105. // }
  106. public virtual X509CertificateStructure CertificateStructure
  107. {
  108. get { return c; }
  109. }
  110. /// <summary>
  111. /// Return true if the current time is within the start and end times nominated on the certificate.
  112. /// </summary>
  113. /// <returns>true id certificate is valid for the current time.</returns>
  114. public virtual bool IsValidNow
  115. {
  116. get { return IsValid(DateTime.UtcNow); }
  117. }
  118. /// <summary>
  119. /// Return true if the nominated time is within the start and end times nominated on the certificate.
  120. /// </summary>
  121. /// <param name="time">The time to test validity against.</param>
  122. /// <returns>True if certificate is valid for nominated time.</returns>
  123. public virtual bool IsValid(
  124. DateTime time)
  125. {
  126. return time.CompareTo(NotBefore) >= 0 && time.CompareTo(NotAfter) <= 0;
  127. }
  128. /// <summary>
  129. /// Checks if the current date is within certificate's validity period.
  130. /// </summary>
  131. public virtual void CheckValidity()
  132. {
  133. this.CheckValidity(DateTime.UtcNow);
  134. }
  135. /// <summary>
  136. /// Checks if the given date is within certificate's validity period.
  137. /// </summary>
  138. /// <exception cref="CertificateExpiredException">if the certificate is expired by given date</exception>
  139. /// <exception cref="CertificateNotYetValidException">if the certificate is not yet valid on given date</exception>
  140. public virtual void CheckValidity(
  141. DateTime time)
  142. {
  143. if (time.CompareTo(NotAfter) > 0)
  144. throw new CertificateExpiredException("certificate expired on " + c.EndDate.GetTime());
  145. if (time.CompareTo(NotBefore) < 0)
  146. throw new CertificateNotYetValidException("certificate not valid until " + c.StartDate.GetTime());
  147. }
  148. /// <summary>
  149. /// Return the certificate's version.
  150. /// </summary>
  151. /// <returns>An integer whose value Equals the version of the cerficate.</returns>
  152. public virtual int Version
  153. {
  154. get { return c.Version; }
  155. }
  156. /// <summary>
  157. /// Return a <see cref="Org.BouncyCastle.Math.BigInteger">BigInteger</see> containing the serial number.
  158. /// </summary>
  159. /// <returns>The Serial number.</returns>
  160. public virtual BigInteger SerialNumber
  161. {
  162. get { return c.SerialNumber.Value; }
  163. }
  164. /// <summary>
  165. /// Get the Issuer Distinguished Name. (Who signed the certificate.)
  166. /// </summary>
  167. /// <returns>And X509Object containing name and value pairs.</returns>
  168. // public IPrincipal IssuerDN
  169. public virtual X509Name IssuerDN
  170. {
  171. get { return c.Issuer; }
  172. }
  173. /// <summary>
  174. /// Get the subject of this certificate.
  175. /// </summary>
  176. /// <returns>An X509Name object containing name and value pairs.</returns>
  177. // public IPrincipal SubjectDN
  178. public virtual X509Name SubjectDN
  179. {
  180. get { return c.Subject; }
  181. }
  182. /// <summary>
  183. /// The time that this certificate is valid from.
  184. /// </summary>
  185. /// <returns>A DateTime object representing that time in the local time zone.</returns>
  186. public virtual DateTime NotBefore
  187. {
  188. get { return c.StartDate.ToDateTime(); }
  189. }
  190. /// <summary>
  191. /// The time that this certificate is valid up to.
  192. /// </summary>
  193. /// <returns>A DateTime object representing that time in the local time zone.</returns>
  194. public virtual DateTime NotAfter
  195. {
  196. get { return c.EndDate.ToDateTime(); }
  197. }
  198. /// <summary>
  199. /// Return the Der encoded TbsCertificate data.
  200. /// This is the certificate component less the signature.
  201. /// To Get the whole certificate call the GetEncoded() member.
  202. /// </summary>
  203. /// <returns>A byte array containing the Der encoded Certificate component.</returns>
  204. public virtual byte[] GetTbsCertificate()
  205. {
  206. return c.TbsCertificate.GetDerEncoded();
  207. }
  208. /// <summary>
  209. /// The signature.
  210. /// </summary>
  211. /// <returns>A byte array containg the signature of the certificate.</returns>
  212. public virtual byte[] GetSignature()
  213. {
  214. return c.GetSignatureOctets();
  215. }
  216. /// <summary>
  217. /// A meaningful version of the Signature Algorithm. (EG SHA1WITHRSA)
  218. /// </summary>
  219. /// <returns>A sting representing the signature algorithm.</returns>
  220. public virtual string SigAlgName
  221. {
  222. get { return SignerUtilities.GetEncodingName(c.SignatureAlgorithm.Algorithm); }
  223. }
  224. /// <summary>
  225. /// Get the Signature Algorithms Object ID.
  226. /// </summary>
  227. /// <returns>A string containg a '.' separated object id.</returns>
  228. public virtual string SigAlgOid
  229. {
  230. get { return c.SignatureAlgorithm.Algorithm.Id; }
  231. }
  232. /// <summary>
  233. /// Get the signature algorithms parameters. (EG DSA Parameters)
  234. /// </summary>
  235. /// <returns>A byte array containing the Der encoded version of the parameters or null if there are none.</returns>
  236. public virtual byte[] GetSigAlgParams()
  237. {
  238. if (c.SignatureAlgorithm.Parameters != null)
  239. {
  240. return c.SignatureAlgorithm.Parameters.GetDerEncoded();
  241. }
  242. return null;
  243. }
  244. /// <summary>
  245. /// Get the issuers UID.
  246. /// </summary>
  247. /// <returns>A DerBitString.</returns>
  248. public virtual DerBitString IssuerUniqueID
  249. {
  250. get { return c.TbsCertificate.IssuerUniqueID; }
  251. }
  252. /// <summary>
  253. /// Get the subjects UID.
  254. /// </summary>
  255. /// <returns>A DerBitString.</returns>
  256. public virtual DerBitString SubjectUniqueID
  257. {
  258. get { return c.TbsCertificate.SubjectUniqueID; }
  259. }
  260. /// <summary>
  261. /// Get a key usage guidlines.
  262. /// </summary>
  263. public virtual bool[] GetKeyUsage()
  264. {
  265. return keyUsage == null ? null : (bool[]) keyUsage.Clone();
  266. }
  267. // TODO Replace with something that returns a list of DerObjectIdentifier
  268. public virtual IList GetExtendedKeyUsage()
  269. {
  270. Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.37"));
  271. if (str == null)
  272. return null;
  273. try
  274. {
  275. Asn1Sequence seq = Asn1Sequence.GetInstance(
  276. X509ExtensionUtilities.FromExtensionValue(str));
  277. IList list = Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  278. foreach (DerObjectIdentifier oid in seq)
  279. {
  280. list.Add(oid.Id);
  281. }
  282. return list;
  283. }
  284. catch (Exception e)
  285. {
  286. throw new CertificateParsingException("error processing extended key usage extension", e);
  287. }
  288. }
  289. public virtual int GetBasicConstraints()
  290. {
  291. if (basicConstraints != null && basicConstraints.IsCA())
  292. {
  293. if (basicConstraints.PathLenConstraint == null)
  294. {
  295. return int.MaxValue;
  296. }
  297. return basicConstraints.PathLenConstraint.IntValue;
  298. }
  299. return -1;
  300. }
  301. public virtual ICollection GetSubjectAlternativeNames()
  302. {
  303. return GetAlternativeNames("2.5.29.17");
  304. }
  305. public virtual ICollection GetIssuerAlternativeNames()
  306. {
  307. return GetAlternativeNames("2.5.29.18");
  308. }
  309. protected virtual ICollection GetAlternativeNames(
  310. string oid)
  311. {
  312. Asn1OctetString altNames = GetExtensionValue(new DerObjectIdentifier(oid));
  313. if (altNames == null)
  314. return null;
  315. Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(altNames);
  316. GeneralNames gns = GeneralNames.GetInstance(asn1Object);
  317. IList result = Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  318. foreach (GeneralName gn in gns.GetNames())
  319. {
  320. IList entry = Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  321. entry.Add(gn.TagNo);
  322. entry.Add(gn.Name.ToString());
  323. result.Add(entry);
  324. }
  325. return result;
  326. }
  327. protected override X509Extensions GetX509Extensions()
  328. {
  329. return c.Version >= 3
  330. ? c.TbsCertificate.Extensions
  331. : null;
  332. }
  333. /// <summary>
  334. /// Get the public key of the subject of the certificate.
  335. /// </summary>
  336. /// <returns>The public key parameters.</returns>
  337. public virtual AsymmetricKeyParameter GetPublicKey()
  338. {
  339. return PublicKeyFactory.CreateKey(c.SubjectPublicKeyInfo);
  340. }
  341. /// <summary>
  342. /// Return a Der encoded version of this certificate.
  343. /// </summary>
  344. /// <returns>A byte array.</returns>
  345. public virtual byte[] GetEncoded()
  346. {
  347. return c.GetDerEncoded();
  348. }
  349. public override bool Equals(
  350. object obj)
  351. {
  352. if (obj == this)
  353. return true;
  354. X509Certificate other = obj as X509Certificate;
  355. if (other == null)
  356. return false;
  357. return c.Equals(other.c);
  358. // NB: May prefer this implementation of Equals if more than one certificate implementation in play
  359. // return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded());
  360. }
  361. public override int GetHashCode()
  362. {
  363. lock (this)
  364. {
  365. if (!hashValueSet)
  366. {
  367. hashValue = c.GetHashCode();
  368. hashValueSet = true;
  369. }
  370. }
  371. return hashValue;
  372. }
  373. // public void setBagAttribute(
  374. // DERObjectIdentifier oid,
  375. // DEREncodable attribute)
  376. // {
  377. // pkcs12Attributes.put(oid, attribute);
  378. // pkcs12Ordering.addElement(oid);
  379. // }
  380. //
  381. // public DEREncodable getBagAttribute(
  382. // DERObjectIdentifier oid)
  383. // {
  384. // return (DEREncodable)pkcs12Attributes.get(oid);
  385. // }
  386. //
  387. // public Enumeration getBagAttributeKeys()
  388. // {
  389. // return pkcs12Ordering.elements();
  390. // }
  391. public override string ToString()
  392. {
  393. StringBuilder buf = new StringBuilder();
  394. string nl = Org.BouncyCastle.Utilities.Platform.NewLine;
  395. buf.Append(" [0] Version: ").Append(this.Version).Append(nl);
  396. buf.Append(" SerialNumber: ").Append(this.SerialNumber).Append(nl);
  397. buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl);
  398. buf.Append(" Start Date: ").Append(this.NotBefore).Append(nl);
  399. buf.Append(" Final Date: ").Append(this.NotAfter).Append(nl);
  400. buf.Append(" SubjectDN: ").Append(this.SubjectDN).Append(nl);
  401. buf.Append(" Public Key: ").Append(this.GetPublicKey()).Append(nl);
  402. buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl);
  403. byte[] sig = this.GetSignature();
  404. buf.Append(" Signature: ").Append(Hex.ToHexString(sig, 0, 20)).Append(nl);
  405. for (int i = 20; i < sig.Length; i += 20)
  406. {
  407. int len = System.Math.Min(20, sig.Length - i);
  408. buf.Append(" ").Append(Hex.ToHexString(sig, i, len)).Append(nl);
  409. }
  410. X509Extensions extensions = c.TbsCertificate.Extensions;
  411. if (extensions != null)
  412. {
  413. IEnumerator e = extensions.ExtensionOids.GetEnumerator();
  414. if (e.MoveNext())
  415. {
  416. buf.Append(" Extensions: \n");
  417. }
  418. do
  419. {
  420. DerObjectIdentifier oid = (DerObjectIdentifier)e.Current;
  421. X509Extension ext = extensions.GetExtension(oid);
  422. if (ext.Value != null)
  423. {
  424. byte[] octs = ext.Value.GetOctets();
  425. Asn1Object obj = Asn1Object.FromByteArray(octs);
  426. buf.Append(" critical(").Append(ext.IsCritical).Append(") ");
  427. try
  428. {
  429. if (oid.Equals(X509Extensions.BasicConstraints))
  430. {
  431. buf.Append(BasicConstraints.GetInstance(obj));
  432. }
  433. else if (oid.Equals(X509Extensions.KeyUsage))
  434. {
  435. buf.Append(KeyUsage.GetInstance(obj));
  436. }
  437. else if (oid.Equals(MiscObjectIdentifiers.NetscapeCertType))
  438. {
  439. buf.Append(new NetscapeCertType((DerBitString) obj));
  440. }
  441. else if (oid.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl))
  442. {
  443. buf.Append(new NetscapeRevocationUrl((DerIA5String) obj));
  444. }
  445. else if (oid.Equals(MiscObjectIdentifiers.VerisignCzagExtension))
  446. {
  447. buf.Append(new VerisignCzagExtension((DerIA5String) obj));
  448. }
  449. else
  450. {
  451. buf.Append(oid.Id);
  452. buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj));
  453. //buf.Append(" value = ").Append("*****").Append(nl);
  454. }
  455. }
  456. catch (Exception)
  457. {
  458. buf.Append(oid.Id);
  459. //buf.Append(" value = ").Append(new string(Hex.encode(ext.getValue().getOctets()))).Append(nl);
  460. buf.Append(" value = ").Append("*****");
  461. }
  462. }
  463. buf.Append(nl);
  464. }
  465. while (e.MoveNext());
  466. }
  467. return buf.ToString();
  468. }
  469. /// <summary>
  470. /// Verify the certificate's signature using the nominated public key.
  471. /// </summary>
  472. /// <param name="key">An appropriate public key parameter object, RsaPublicKeyParameters, DsaPublicKeyParameters or ECDsaPublicKeyParameters</param>
  473. /// <returns>True if the signature is valid.</returns>
  474. /// <exception cref="Exception">If key submitted is not of the above nominated types.</exception>
  475. public virtual void Verify(
  476. AsymmetricKeyParameter key)
  477. {
  478. CheckSignature(new Asn1VerifierFactory(c.SignatureAlgorithm, key));
  479. }
  480. /// <summary>
  481. /// Verify the certificate's signature using a verifier created using the passed in verifier provider.
  482. /// </summary>
  483. /// <param name="verifierProvider">An appropriate provider for verifying the certificate's signature.</param>
  484. /// <returns>True if the signature is valid.</returns>
  485. /// <exception cref="Exception">If verifier provider is not appropriate or the certificate algorithm is invalid.</exception>
  486. public virtual void Verify(
  487. IVerifierFactoryProvider verifierProvider)
  488. {
  489. CheckSignature(verifierProvider.CreateVerifierFactory (c.SignatureAlgorithm));
  490. }
  491. protected virtual void CheckSignature(
  492. IVerifierFactory verifier)
  493. {
  494. if (!IsAlgIDEqual(c.SignatureAlgorithm, c.TbsCertificate.Signature))
  495. throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
  496. //Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
  497. IStreamCalculator streamCalculator = verifier.CreateCalculator();
  498. byte[] b = this.GetTbsCertificate();
  499. streamCalculator.Stream.Write(b, 0, b.Length);
  500. Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
  501. if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature()))
  502. {
  503. throw new InvalidKeyException("Public key presented not for certificate signature");
  504. }
  505. }
  506. private static bool IsAlgIDEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2)
  507. {
  508. if (!id1.Algorithm.Equals(id2.Algorithm))
  509. return false;
  510. Asn1Encodable p1 = id1.Parameters;
  511. Asn1Encodable p2 = id2.Parameters;
  512. if ((p1 == null) == (p2 == null))
  513. return Org.BouncyCastle.Utilities.Platform.Equals(p1, p2);
  514. // Exactly one of p1, p2 is null at this point
  515. return p1 == null
  516. ? p2.ToAsn1Object() is Asn1Null
  517. : p1.ToAsn1Object() is Asn1Null;
  518. }
  519. }
  520. }
  521. #endif