MiscPemGenerator.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. encoding = EncodePrivateKey(akp, out type);
  93. }
  94. else
  95. {
  96. type = "PUBLIC KEY";
  97. encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded();
  98. }
  99. }
  100. else if (obj is IX509AttributeCertificate)
  101. {
  102. type = "ATTRIBUTE CERTIFICATE";
  103. encoding = ((X509V2AttributeCertificate)obj).GetEncoded();
  104. }
  105. else if (obj is Pkcs10CertificationRequest)
  106. {
  107. type = "CERTIFICATE REQUEST";
  108. encoding = ((Pkcs10CertificationRequest)obj).GetEncoded();
  109. }
  110. else if (obj is Asn1.Cms.ContentInfo)
  111. {
  112. type = "PKCS7";
  113. encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded();
  114. }
  115. else
  116. {
  117. throw new PemGenerationException("Object type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
  118. }
  119. return new PemObject(type, encoding);
  120. }
  121. // private string GetHexEncoded(byte[] bytes)
  122. // {
  123. // bytes = Hex.Encode(bytes);
  124. //
  125. // char[] chars = new char[bytes.Length];
  126. //
  127. // for (int i = 0; i != bytes.Length; i++)
  128. // {
  129. // chars[i] = (char)bytes[i];
  130. // }
  131. //
  132. // return new string(chars);
  133. // }
  134. private static PemObject CreatePemObject(
  135. object obj,
  136. string algorithm,
  137. char[] password,
  138. SecureRandom random)
  139. {
  140. if (obj == null)
  141. throw new ArgumentNullException("obj");
  142. if (algorithm == null)
  143. throw new ArgumentNullException("algorithm");
  144. if (password == null)
  145. throw new ArgumentNullException("password");
  146. if (random == null)
  147. throw new ArgumentNullException("random");
  148. if (obj is AsymmetricCipherKeyPair)
  149. {
  150. return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private, algorithm, password, random);
  151. }
  152. string type = null;
  153. byte[] keyData = null;
  154. if (obj is AsymmetricKeyParameter)
  155. {
  156. AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj;
  157. if (akp.IsPrivate)
  158. {
  159. keyData = EncodePrivateKey(akp, out type);
  160. }
  161. }
  162. if (type == null || keyData == null)
  163. {
  164. // TODO Support other types?
  165. throw new PemGenerationException("Object type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
  166. }
  167. string dekAlgName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
  168. // Note: For backward compatibility
  169. if (dekAlgName == "DESEDE")
  170. {
  171. dekAlgName = "DES-EDE3-CBC";
  172. }
  173. int ivLength = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(dekAlgName, "AES-") ? 16 : 8;
  174. byte[] iv = new byte[ivLength];
  175. random.NextBytes(iv);
  176. byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv);
  177. IList headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(2);
  178. headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
  179. headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv)));
  180. return new PemObject(type, headers, encData);
  181. }
  182. private static byte[] EncodePrivateKey(
  183. AsymmetricKeyParameter akp,
  184. out string keyType)
  185. {
  186. PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp);
  187. AlgorithmIdentifier algID = info.PrivateKeyAlgorithm;
  188. DerObjectIdentifier oid = algID.Algorithm;
  189. if (oid.Equals(X9ObjectIdentifiers.IdDsa))
  190. {
  191. keyType = "DSA PRIVATE KEY";
  192. DsaParameter p = DsaParameter.GetInstance(algID.Parameters);
  193. BigInteger x = ((DsaPrivateKeyParameters) akp).X;
  194. BigInteger y = p.G.ModPow(x, p.P);
  195. // TODO Create an ASN1 object somewhere for this?
  196. return new DerSequence(
  197. new DerInteger(0),
  198. new DerInteger(p.P),
  199. new DerInteger(p.Q),
  200. new DerInteger(p.G),
  201. new DerInteger(y),
  202. new DerInteger(x)).GetEncoded();
  203. }
  204. if (oid.Equals(PkcsObjectIdentifiers.RsaEncryption))
  205. {
  206. keyType = "RSA PRIVATE KEY";
  207. return info.ParsePrivateKey().GetEncoded();
  208. }
  209. else if (oid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)
  210. || oid.Equals(X9ObjectIdentifiers.IdECPublicKey))
  211. {
  212. keyType = "EC PRIVATE KEY";
  213. return info.ParsePrivateKey().GetEncoded();
  214. }
  215. else
  216. {
  217. keyType = "PRIVATE KEY";
  218. return info.GetEncoded();
  219. }
  220. }
  221. public PemObject Generate()
  222. {
  223. try
  224. {
  225. if (algorithm != null)
  226. {
  227. return CreatePemObject(obj, algorithm, password, random);
  228. }
  229. return CreatePemObject(obj);
  230. }
  231. catch (IOException e)
  232. {
  233. throw new PemGenerationException("encoding exception", e);
  234. }
  235. }
  236. }
  237. }
  238. #pragma warning restore
  239. #endif