MiscPemGenerator.cs 9.2 KB

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