X509Certificate.cs 25 KB

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