X509V3CertificateGenerator.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Math;
  10. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
  11. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  12. using Best.HTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
  13. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.X509
  14. {
  15. /// <summary>
  16. /// A class to Generate Version 3 X509Certificates.
  17. /// </summary>
  18. public class X509V3CertificateGenerator
  19. {
  20. private readonly X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator();
  21. private V3TbsCertificateGenerator tbsGen;
  22. public X509V3CertificateGenerator()
  23. {
  24. tbsGen = new V3TbsCertificateGenerator();
  25. }
  26. /// <summary>
  27. /// Reset the Generator.
  28. /// </summary>
  29. public void Reset()
  30. {
  31. tbsGen = new V3TbsCertificateGenerator();
  32. extGenerator.Reset();
  33. }
  34. /// <summary>
  35. /// Set the certificate's serial number.
  36. /// </summary>
  37. /// <remarks>Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
  38. /// You will be surprised how ugly a serial number collision can Get.</remarks>
  39. /// <param name="serialNumber">The serial number.</param>
  40. public void SetSerialNumber(
  41. BigInteger serialNumber)
  42. {
  43. if (serialNumber.SignValue <= 0)
  44. {
  45. throw new ArgumentException("serial number must be a positive integer", "serialNumber");
  46. }
  47. tbsGen.SetSerialNumber(new DerInteger(serialNumber));
  48. }
  49. /// <summary>
  50. /// Set the distinguished name of the issuer.
  51. /// The issuer is the entity which is signing the certificate.
  52. /// </summary>
  53. /// <param name="issuer">The issuer's DN.</param>
  54. public void SetIssuerDN(
  55. X509Name issuer)
  56. {
  57. tbsGen.SetIssuer(issuer);
  58. }
  59. /// <summary>
  60. /// Set the date that this certificate is to be valid from.
  61. /// </summary>
  62. /// <param name="date"/>
  63. public void SetNotBefore(
  64. DateTime date)
  65. {
  66. tbsGen.SetStartDate(new Time(date));
  67. }
  68. /// <summary>
  69. /// Set the date after which this certificate will no longer be valid.
  70. /// </summary>
  71. /// <param name="date"/>
  72. public void SetNotAfter(
  73. DateTime date)
  74. {
  75. tbsGen.SetEndDate(new Time(date));
  76. }
  77. /// <summary>
  78. /// Set the DN of the entity that this certificate is about.
  79. /// </summary>
  80. /// <param name="subject"/>
  81. public void SetSubjectDN(
  82. X509Name subject)
  83. {
  84. tbsGen.SetSubject(subject);
  85. }
  86. /// <summary>
  87. /// Set the public key that this certificate identifies.
  88. /// </summary>
  89. /// <param name="publicKey"/>
  90. public void SetPublicKey(
  91. AsymmetricKeyParameter publicKey)
  92. {
  93. tbsGen.SetSubjectPublicKeyInfo(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey));
  94. }
  95. /// <summary>
  96. /// Set the subject unique ID - note: it is very rare that it is correct to do this.
  97. /// </summary>
  98. /// <param name="uniqueID"/>
  99. public void SetSubjectUniqueID(
  100. bool[] uniqueID)
  101. {
  102. tbsGen.SetSubjectUniqueID(booleanToBitString(uniqueID));
  103. }
  104. /// <summary>
  105. /// Set the issuer unique ID - note: it is very rare that it is correct to do this.
  106. /// </summary>
  107. /// <param name="uniqueID"/>
  108. public void SetIssuerUniqueID(
  109. bool[] uniqueID)
  110. {
  111. tbsGen.SetIssuerUniqueID(booleanToBitString(uniqueID));
  112. }
  113. private DerBitString booleanToBitString(
  114. bool[] id)
  115. {
  116. byte[] bytes = new byte[(id.Length + 7) / 8];
  117. for (int i = 0; i != id.Length; i++)
  118. {
  119. if (id[i])
  120. {
  121. bytes[i / 8] |= (byte)(1 << ((7 - (i % 8))));
  122. }
  123. }
  124. int pad = id.Length % 8;
  125. if (pad == 0)
  126. {
  127. return new DerBitString(bytes);
  128. }
  129. return new DerBitString(bytes, 8 - pad);
  130. }
  131. /// <summary>
  132. /// Add a given extension field for the standard extensions tag (tag 3).
  133. /// </summary>
  134. /// <param name="oid">string containing a dotted decimal Object Identifier.</param>
  135. /// <param name="critical">Is it critical.</param>
  136. /// <param name="extensionValue">The value.</param>
  137. public void AddExtension(
  138. string oid,
  139. bool critical,
  140. Asn1Encodable extensionValue)
  141. {
  142. extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, extensionValue);
  143. }
  144. /// <summary>
  145. /// Add an extension to this certificate.
  146. /// </summary>
  147. /// <param name="oid">Its Object Identifier.</param>
  148. /// <param name="critical">Is it critical.</param>
  149. /// <param name="extensionValue">The value.</param>
  150. public void AddExtension(
  151. DerObjectIdentifier oid,
  152. bool critical,
  153. Asn1Encodable extensionValue)
  154. {
  155. extGenerator.AddExtension(oid, critical, extensionValue);
  156. }
  157. /// <summary>
  158. /// Add an extension using a string with a dotted decimal OID.
  159. /// </summary>
  160. /// <param name="oid">string containing a dotted decimal Object Identifier.</param>
  161. /// <param name="critical">Is it critical.</param>
  162. /// <param name="extensionValue">byte[] containing the value of this extension.</param>
  163. public void AddExtension(
  164. string oid,
  165. bool critical,
  166. byte[] extensionValue)
  167. {
  168. extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, new DerOctetString(extensionValue));
  169. }
  170. /// <summary>
  171. /// Add an extension to this certificate.
  172. /// </summary>
  173. /// <param name="oid">Its Object Identifier.</param>
  174. /// <param name="critical">Is it critical.</param>
  175. /// <param name="extensionValue">byte[] containing the value of this extension.</param>
  176. public void AddExtension(
  177. DerObjectIdentifier oid,
  178. bool critical,
  179. byte[] extensionValue)
  180. {
  181. extGenerator.AddExtension(oid, critical, new DerOctetString(extensionValue));
  182. }
  183. /// <summary>
  184. /// Add a given extension field for the standard extensions tag (tag 3),
  185. /// copying the extension value from another certificate.
  186. /// </summary>
  187. public void CopyAndAddExtension(
  188. string oid,
  189. bool critical,
  190. X509Certificate cert)
  191. {
  192. CopyAndAddExtension(new DerObjectIdentifier(oid), critical, cert);
  193. }
  194. /**
  195. * add a given extension field for the standard extensions tag (tag 3)
  196. * copying the extension value from another certificate.
  197. * @throws CertificateParsingException if the extension cannot be extracted.
  198. */
  199. public void CopyAndAddExtension(
  200. DerObjectIdentifier oid,
  201. bool critical,
  202. X509Certificate cert)
  203. {
  204. Asn1OctetString extValue = cert.GetExtensionValue(oid);
  205. if (extValue == null)
  206. throw new CertificateParsingException("extension " + oid + " not present");
  207. try
  208. {
  209. Asn1Encodable value = X509ExtensionUtilities.FromExtensionValue(extValue);
  210. this.AddExtension(oid, critical, value);
  211. }
  212. catch (Exception e)
  213. {
  214. throw new CertificateParsingException(e.Message, e);
  215. }
  216. }
  217. /// <summary>
  218. /// Generate a new <see cref="X509Certificate"/> using the provided <see cref="ISignatureFactory"/>.
  219. /// </summary>
  220. /// <param name="signatureFactory">A <see cref="ISignatureFactory">signature factory</see> with the necessary
  221. /// algorithm details.</param>
  222. /// <returns>An <see cref="X509Certificate"/>.</returns>
  223. public X509Certificate Generate(ISignatureFactory signatureFactory)
  224. {
  225. var sigAlgID = (AlgorithmIdentifier)signatureFactory.AlgorithmDetails;
  226. tbsGen.SetSignature(sigAlgID);
  227. if (!extGenerator.IsEmpty)
  228. {
  229. tbsGen.SetExtensions(extGenerator.Generate());
  230. }
  231. TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();
  232. IStreamCalculator<IBlockResult> streamCalculator = signatureFactory.CreateCalculator();
  233. using (Stream sigStream = streamCalculator.Stream)
  234. {
  235. tbsCert.EncodeTo(sigStream, Asn1Encodable.Der);
  236. }
  237. var signature = streamCalculator.GetResult().Collect();
  238. return new X509Certificate(new X509CertificateStructure(tbsCert, sigAlgID, new DerBitString(signature)));
  239. }
  240. /// <summary>
  241. /// Allows enumeration of the signature names supported by the generator.
  242. /// </summary>
  243. public IEnumerable<string> SignatureAlgNames
  244. {
  245. get { return X509Utilities.GetAlgNames(); }
  246. }
  247. }
  248. }
  249. #pragma warning restore
  250. #endif