X509Certificate.cs 18 KB

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