CertificateGenerator.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Collections;
  4. using System.Security.Cryptography;
  5. namespace Emby.Common.Implementations.Security
  6. {
  7. internal class CertificateGenerator
  8. {
  9. private const string MonoTestRootAgency = "<RSAKeyValue><Modulus>v/4nALBxCE+9JgEC0LnDUvKh6e96PwTpN4Rj+vWnqKT7IAp1iK/JjuqvAg6DQ2vTfv0dTlqffmHH51OyioprcT5nzxcSTsZb/9jcHScG0s3/FRIWnXeLk/fgm7mSYhjUaHNI0m1/NTTktipicjKxo71hGIg9qucCWnDum+Krh/k=</Modulus><Exponent>AQAB</Exponent><P>9jbKxMXEruW2CfZrzhxtull4O8P47+mNsEL+9gf9QsRO1jJ77C+jmzfU6zbzjf8+ViK+q62tCMdC1ZzulwdpXQ==</P><Q>x5+p198l1PkK0Ga2mRh0SIYSykENpY2aLXoyZD/iUpKYAvATm0/wvKNrE4dKJyPCA+y3hfTdgVag+SP9avvDTQ==</Q><DP>ISSjCvXsUfbOGG05eddN1gXxL2pj+jegQRfjpk7RAsnWKvNExzhqd5x+ZuNQyc6QH5wxun54inP4RTUI0P/IaQ==</DP><DQ>R815VQmR3RIbPqzDXzv5j6CSH6fYlcTiQRtkBsUnzhWmkd/y3XmamO+a8zJFjOCCx9CcjpVuGziivBqi65lVPQ==</DQ><InverseQ>iYiu0KwMWI/dyqN3RJYUzuuLj02/oTD1pYpwo2rvNCXU1Q5VscOeu2DpNg1gWqI+1RrRCsEoaTNzXB1xtKNlSw==</InverseQ><D>nIfh1LYF8fjRBgMdAH/zt9UKHWiaCnc+jXzq5tkR8HVSKTVdzitD8bl1JgAfFQD8VjSXiCJqluexy/B5SGrCXQ49c78NIQj0hD+J13Y8/E0fUbW1QYbhj6Ff7oHyhaYe1WOQfkp2t/h+llHOdt1HRf7bt7dUknYp7m8bQKGxoYE=</D></RSAKeyValue>";
  10. internal static void CreateSelfSignCertificatePfx(
  11. string fileName,
  12. string hostname,
  13. ILogger logger)
  14. {
  15. if (string.IsNullOrWhiteSpace(fileName))
  16. {
  17. throw new ArgumentNullException("fileName");
  18. }
  19. byte[] sn = Guid.NewGuid().ToByteArray();
  20. string subject = string.Format("CN={0}", hostname);
  21. string issuer = subject;
  22. DateTime notBefore = DateTime.Now.AddDays(-2);
  23. DateTime notAfter = DateTime.Now.AddYears(10);
  24. RSA issuerKey = RSA.Create();
  25. issuerKey.FromXmlString(MonoTestRootAgency);
  26. RSA subjectKey = RSA.Create();
  27. // serial number MUST be positive
  28. if ((sn[0] & 0x80) == 0x80)
  29. sn[0] -= 0x80;
  30. issuer = subject;
  31. issuerKey = subjectKey;
  32. X509CertificateBuilder cb = new X509CertificateBuilder(3);
  33. cb.SerialNumber = sn;
  34. cb.IssuerName = issuer;
  35. cb.NotBefore = notBefore;
  36. cb.NotAfter = notAfter;
  37. cb.SubjectName = subject;
  38. cb.SubjectPublicKey = subjectKey;
  39. // signature
  40. cb.Hash = "SHA256";
  41. byte[] rawcert = cb.Sign(issuerKey);
  42. PKCS12 p12 = new PKCS12();
  43. ArrayList list = new ArrayList();
  44. // we use a fixed array to avoid endianess issues
  45. // (in case some tools requires the ID to be 1).
  46. list.Add(new byte[4] { 1, 0, 0, 0 });
  47. Hashtable attributes = new Hashtable(1);
  48. attributes.Add(PKCS9.localKeyId, list);
  49. p12.AddCertificate(new X509Certificate(rawcert), attributes);
  50. p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes);
  51. p12.SaveToFile(fileName);
  52. }
  53. }
  54. }