X509Certificate.cs 27 KB

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