PfxGenerator.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections;
  3. using System.Security.Cryptography;
  4. namespace Emby.Server.Core.Cryptography
  5. {
  6. public class PFXGenerator
  7. {
  8. // http://www.freekpaans.nl/2015/04/creating-self-signed-x-509-certificates-using-mono-security/
  9. public static byte[] GeneratePfx(string certificateName, string password)
  10. {
  11. byte[] sn = GenerateSerialNumber();
  12. string subject = string.Format("CN={0}", certificateName);
  13. DateTime notBefore = DateTime.Now;
  14. DateTime notAfter = DateTime.Now.AddYears(20);
  15. RSA subjectKey = new RSACryptoServiceProvider(2048);
  16. string hashName = "SHA256";
  17. X509CertificateBuilder cb = new X509CertificateBuilder(3);
  18. cb.SerialNumber = sn;
  19. cb.IssuerName = subject;
  20. cb.NotBefore = notBefore;
  21. cb.NotAfter = notAfter;
  22. cb.SubjectName = subject;
  23. cb.SubjectPublicKey = subjectKey;
  24. cb.Hash = hashName;
  25. byte[] rawcert = cb.Sign(subjectKey);
  26. PKCS12 p12 = new PKCS12();
  27. p12.Password = password;
  28. Hashtable attributes = GetAttributes();
  29. p12.AddCertificate(new X509Certificate(rawcert), attributes);
  30. p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes);
  31. return p12.GetBytes();
  32. }
  33. private static Hashtable GetAttributes()
  34. {
  35. ArrayList list = new ArrayList();
  36. // we use a fixed array to avoid endianess issues
  37. // (in case some tools requires the ID to be 1).
  38. list.Add(new byte[4] { 1, 0, 0, 0 });
  39. Hashtable attributes = new Hashtable(1);
  40. attributes.Add(PKCS9.localKeyId, list);
  41. return attributes;
  42. }
  43. private static byte[] GenerateSerialNumber()
  44. {
  45. byte[] sn = Guid.NewGuid().ToByteArray();
  46. //must be positive
  47. if ((sn[0] & 0x80) == 0x80)
  48. sn[0] -= 0x80;
  49. return sn;
  50. }
  51. public static byte[] GetCertificateForBytes(byte[] pfx, string password)
  52. {
  53. var pkcs = new PKCS12(pfx, password);
  54. var cert = pkcs.GetCertificate(GetAttributes());
  55. return cert.RawData;
  56. }
  57. }
  58. }