MiscPemGenerator.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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.CryptoPro;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  10. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
  11. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  12. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  13. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Math;
  14. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Pkcs;
  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.Utilities.IO.Pem;
  20. using Best.HTTP.SecureProtocol.Org.BouncyCastle.X509;
  21. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.OpenSsl
  22. {
  23. /**
  24. * PEM generator for the original set of PEM objects used in Open SSL.
  25. */
  26. public class MiscPemGenerator
  27. : PemObjectGenerator
  28. {
  29. private readonly object obj;
  30. private readonly string algorithm;
  31. private readonly char[] password;
  32. private readonly SecureRandom random;
  33. public MiscPemGenerator(object obj)
  34. {
  35. this.obj = obj;
  36. }
  37. public MiscPemGenerator(
  38. object obj,
  39. string algorithm,
  40. char[] password,
  41. SecureRandom random)
  42. {
  43. this.obj = obj;
  44. this.algorithm = algorithm;
  45. this.password = password;
  46. this.random = random;
  47. }
  48. private static PemObject CreatePemObject(object obj)
  49. {
  50. if (obj == null)
  51. throw new ArgumentNullException("obj");
  52. if (obj is AsymmetricCipherKeyPair keyPair)
  53. {
  54. return CreatePemObject(keyPair.Private);
  55. }
  56. string type;
  57. byte[] encoding;
  58. if (obj is PemObject pemObject)
  59. return pemObject;
  60. if (obj is PemObjectGenerator pemObjectGenerator)
  61. return pemObjectGenerator.Generate();
  62. if (obj is X509Certificate certificate)
  63. {
  64. // TODO Should we prefer "X509 CERTIFICATE" here?
  65. type = "CERTIFICATE";
  66. try
  67. {
  68. encoding = certificate.GetEncoded();
  69. }
  70. catch (CertificateEncodingException e)
  71. {
  72. throw new IOException("Cannot Encode object: " + e.ToString());
  73. }
  74. }
  75. else if (obj is X509Crl crl)
  76. {
  77. type = "X509 CRL";
  78. try
  79. {
  80. encoding = crl.GetEncoded();
  81. }
  82. catch (CrlException e)
  83. {
  84. throw new IOException("Cannot Encode object: " + e.ToString());
  85. }
  86. }
  87. else if (obj is AsymmetricKeyParameter akp)
  88. {
  89. if (akp.IsPrivate)
  90. {
  91. encoding = EncodePrivateKey(akp, out type);
  92. }
  93. else
  94. {
  95. type = "PUBLIC KEY";
  96. encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded();
  97. }
  98. }
  99. else if (obj is X509V2AttributeCertificate attrCert)
  100. {
  101. type = "ATTRIBUTE CERTIFICATE";
  102. encoding = attrCert.GetEncoded();
  103. }
  104. else if (obj is Pkcs10CertificationRequest certReq)
  105. {
  106. type = "CERTIFICATE REQUEST";
  107. encoding = certReq.GetEncoded();
  108. }
  109. else if (obj is Asn1.Cms.ContentInfo contentInfo)
  110. {
  111. type = "PKCS7";
  112. encoding = contentInfo.GetEncoded();
  113. }
  114. else
  115. {
  116. throw new PemGenerationException("Object type not supported: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
  117. }
  118. return new PemObject(type, encoding);
  119. }
  120. // private string GetHexEncoded(byte[] bytes)
  121. // {
  122. // bytes = Hex.Encode(bytes);
  123. //
  124. // char[] chars = new char[bytes.Length];
  125. //
  126. // for (int i = 0; i != bytes.Length; i++)
  127. // {
  128. // chars[i] = (char)bytes[i];
  129. // }
  130. //
  131. // return new string(chars);
  132. // }
  133. private static PemObject CreatePemObject(
  134. object obj,
  135. string algorithm,
  136. char[] password,
  137. SecureRandom random)
  138. {
  139. if (obj == null)
  140. throw new ArgumentNullException("obj");
  141. if (algorithm == null)
  142. throw new ArgumentNullException("algorithm");
  143. if (password == null)
  144. throw new ArgumentNullException("password");
  145. if (random == null)
  146. throw new ArgumentNullException("random");
  147. if (obj is AsymmetricCipherKeyPair keyPair)
  148. {
  149. return CreatePemObject(keyPair.Private, algorithm, password, random);
  150. }
  151. string type = null;
  152. byte[] keyData = null;
  153. if (obj is AsymmetricKeyParameter akp)
  154. {
  155. if (akp.IsPrivate)
  156. {
  157. keyData = EncodePrivateKey(akp, out type);
  158. }
  159. }
  160. if (type == null || keyData == null)
  161. {
  162. // TODO Support other types?
  163. throw new PemGenerationException("Object type not supported: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
  164. }
  165. string dekAlgName = algorithm.ToUpperInvariant();
  166. // Note: For backward compatibility
  167. if (dekAlgName == "DESEDE")
  168. {
  169. dekAlgName = "DES-EDE3-CBC";
  170. }
  171. int ivLength = Org.BouncyCastle.Utilities.Platform.StartsWith(dekAlgName, "AES-") ? 16 : 8;
  172. byte[] iv = new byte[ivLength];
  173. random.NextBytes(iv);
  174. byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv);
  175. var headers = new List<PemHeader>(2);
  176. headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
  177. headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv).ToUpperInvariant()));
  178. return new PemObject(type, headers, encData);
  179. }
  180. private static byte[] EncodePrivateKey(
  181. AsymmetricKeyParameter akp,
  182. out string keyType)
  183. {
  184. PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp);
  185. AlgorithmIdentifier algID = info.PrivateKeyAlgorithm;
  186. DerObjectIdentifier oid = algID.Algorithm;
  187. if (oid.Equals(X9ObjectIdentifiers.IdDsa))
  188. {
  189. keyType = "DSA PRIVATE KEY";
  190. DsaParameter p = DsaParameter.GetInstance(algID.Parameters);
  191. BigInteger x = ((DsaPrivateKeyParameters) akp).X;
  192. BigInteger y = p.G.ModPow(x, p.P);
  193. // TODO Create an ASN1 object somewhere for this?
  194. return new DerSequence(
  195. new DerInteger(0),
  196. new DerInteger(p.P),
  197. new DerInteger(p.Q),
  198. new DerInteger(p.G),
  199. new DerInteger(y),
  200. new DerInteger(x)).GetEncoded();
  201. }
  202. if (oid.Equals(PkcsObjectIdentifiers.RsaEncryption))
  203. {
  204. keyType = "RSA PRIVATE KEY";
  205. return info.ParsePrivateKey().GetEncoded();
  206. }
  207. else if (oid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)
  208. || oid.Equals(X9ObjectIdentifiers.IdECPublicKey))
  209. {
  210. keyType = "EC PRIVATE KEY";
  211. return info.ParsePrivateKey().GetEncoded();
  212. }
  213. else
  214. {
  215. keyType = "PRIVATE KEY";
  216. return info.GetEncoded();
  217. }
  218. }
  219. public PemObject Generate()
  220. {
  221. try
  222. {
  223. if (algorithm != null)
  224. {
  225. return CreatePemObject(obj, algorithm, password, random);
  226. }
  227. return CreatePemObject(obj);
  228. }
  229. catch (IOException e)
  230. {
  231. throw new PemGenerationException("encoding exception", e);
  232. }
  233. }
  234. }
  235. }
  236. #pragma warning restore
  237. #endif