示例#1
0
        /// <summary>
        /// Creates a self-signed certificate
        /// http://stackoverflow.com/questions/13806299/how-to-create-a-self-signed-certificate-using-c
        /// </summary>
        /// <param name="subjectName"></param>
        /// <returns></returns>
        public static X509Certificate2 CreateSelfSignedCertificate(params string[] commonNames)
        {
            using (var ctx = new CryptContext())
            {
                ctx.Open();

                var nameBuilder = new StringBuilder();
                foreach (var commonName in commonNames)
                {
                    nameBuilder.AppendLine($"CN={commonName}");
                }

                var certificate = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName(nameBuilder.ToString(), X500DistinguishedNameFlags.UseNewLines),
                    ValidFrom = DateTime.Today.AddDays(-1),
                    ValidTo   = DateTime.Today.AddYears(1)
                });

                return(certificate);
            }
        }
示例#2
0
        public static void InstallServantCertificate()
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);

            //CRASH!
            // Servant certifikatet kan ikke bindes til Azure serveren, ved mindre det bliver eksporteret og importeret først. Den siger det der med local user blablal..

            X509Certificate2 cert;

            using (var ctx = new CryptContext())
            {
                ctx.Open();
                cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName("CN=\"Servant\"; C=\"Denmark\"; O=\"Denmark\"; OU=\"Denmark\";"),
                    ValidFrom = DateTime.Today,
                    ValidTo   = DateTime.Today.AddYears(10)
                });
            }
            cert.FriendlyName = "Servant";
            store.Add(cert);
            store.Close();

            System.Threading.Thread.Sleep(1000); // Wait for certificate to be installed
        }
示例#3
0
        public static void InstallServantCertificate(string name)
        {
            var store = OpenStore(OpenFlags.ReadWrite);
            X509Certificate2 cert;

            using (var ctx = new CryptContext())
            {
                ctx.Open();
                cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName(string.Format("CN=\"{0}\"; C=\"{0}\"; O=\"{0}\"; OU=\"{0}\";", name)),
                    ValidFrom = DateTime.Today,
                    ValidTo   = DateTime.Today.AddYears(10),
                });
                //ensure pfx in cert.
                byte[] pfx     = cert.Export(X509ContentType.Pfx);
                byte[] pkbytes = cert.Export(X509ContentType.Cert);
                System.IO.File.WriteAllBytes(string.Format(".\\{0}.cer", name), pkbytes);
                cert = new X509Certificate2(pfx, (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            }
            cert.FriendlyName = name;
            store.Add(cert);
            store.Close();
            System.Threading.Thread.Sleep(1000); // Wait for certificate to be installed
        }
示例#4
0
        public static CertificateStore CreateCertificate()
        {
            using (var ctx = new CryptContext())
            {
                ctx.Open();
                var cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName(CERT_DISTINGUISHED_NAME),
                    ValidFrom = DateTime.Today.AddDays(-1),
                    ValidTo   = DateTime.Today.AddYears(1),
                });

                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

                var storePermissions = new StorePermission(PermissionState.Unrestricted);
                storePermissions.Flags = StorePermissionFlags.OpenStore;
                storePermissions.Assert();

                store.Open(OpenFlags.ReadWrite);
                X509Certificate2Collection collection = new X509Certificate2Collection();

                collection.Add(cert);
                store.AddRange(collection);
                store.Close();

                return(new CertificateStore(cert));
            }
        }
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            backgroundThreadId = GetCurrentThreadId();

            using (CryptContext ctx = new CryptContext())
            {
                ctx.Open();

                Certificate = ctx.CreateSelfSignedCertificate(CertProperties);
            }

            BeginInvoke(new Action(BackroundWorkerFinished), null);
        }
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            backgroundThreadId = GetCurrentThreadId();

            using (CryptContext ctx = new CryptContext())
            {
                ctx.Open();

                Certificate = ctx.CreateSelfSignedCertificate(CertProperties);
            }

            BeginInvoke(new Action(BackroundWorkerFinished), null);
        }
示例#7
0
        private static X509Certificate2 GenerateCertificate()
        {
            string certName = new Uri(WebApiShared.BaseAddress).DnsSafeHost;

            using (var ctx = new CryptContext())
            {
                ctx.Open();
                return(ctx.CreateSelfSignedCertificate(
                           new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength = 4096,
                    Name = new X500DistinguishedName($"cn={certName}"),
                    ValidFrom = DateTime.Today.AddDays(-1),
                    ValidTo = DateTime.Today.AddYears(1),
                }));
            }
        }
示例#8
0
        // here's a simple example of how to gen a cert programmatically using Pluralsight.Crypto
        // note you'll need to also reference System.Security.dll to get support for X509Certificate2UI.
        static void GenSelfSignedCert()
        {
            using (CryptContext ctx = new CryptContext())
            {
                ctx.Open();

                X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName("cn=localhost"),
                    ValidFrom = DateTime.Today.AddDays(-1),
                    ValidTo   = DateTime.Today.AddYears(1),
                });

                X509Certificate2UI.DisplayCertificate(cert);
            }
        }
示例#9
0
        public static X509Certificate2 GenerateCertificate()
        {
            using (CryptContext ctx = new CryptContext())
            {
                ctx.Open();

                X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 1024,
                    Name = new X500DistinguishedName("cn=localhost"),

                    ValidFrom = DateTime.Now,
                    ValidTo   = DateTime.Now.AddDays(1),
                });

                return(cert);
            }
        }
示例#10
0
        public static X509Certificate2 GenSelfSignedCert(string commonName, DateTime validFrom, DateTime validTo)
        {
            using (CryptContext ctx = new CryptContext())
            {
                ctx.Open();

                X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName("CN=" + commonName),
                    ValidFrom = validFrom,
                    ValidTo   = validTo,
                });


                return(cert);
            }
        }
示例#11
0
        internal static void GenerateCertificate(
            IFileSystem fileSystem,
            string pathToPfx,
            string pathToCer,
            string issuer,
            string password,
            DateTime validity)
        {
            using (CryptContext ctx = new CryptContext())
            {
                ctx.Open();

                X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 2048,
                    Name      = new X500DistinguishedName($"cn={issuer}"),
                    ValidFrom = DateTime.Today.AddDays(-1),
                    ValidTo   = validity
                });

                if (fileSystem.FileExists(pathToPfx))
                {
                    fileSystem.DeleteFile(pathToPfx);
                }

                fileSystem.WriteAllBytesToFile(pathToPfx, cert.Export(X509ContentType.Pfx, password));

                if (fileSystem.FileExists(pathToCer))
                {
                    fileSystem.DeleteFile(pathToCer);
                }

                fileSystem.WriteAllTextToFile(pathToCer,
                                              "-----BEGIN CERTIFICATE-----\r\n"
                                              + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
                                              + "\r\n-----END CERTIFICATE-----");
            }
        }
示例#12
0
        private static void CreateCertificate(string cn)
        {
            Console.WriteLine("Creating certificate...");
            using (CryptContext ctx = new CryptContext())
            {
                ctx.Open();

                X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName($"cn={cn}"),
                    ValidFrom = DateTime.Today.AddDays(-1),
                    ValidTo   = DateTime.Today.AddYears(1),
                }
                    );

                byte[] certFileRaw = cert.Export(X509ContentType.Pfx, "banaantje");
                string filePath    = Directory.GetCurrentDirectory() + "\\certificate.pfx";

                File.WriteAllBytes(filePath, certFileRaw);

                File.WriteAllText(Directory.GetCurrentDirectory() + "\\certificate.cer",
                                  "-----BEGIN CERTIFICATE-----\r\n"
                                  + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
                                  + "\r\n-----END CERTIFICATE-----"
                                  );
                Console.WriteLine("Done");

                Console.WriteLine("Adding to store...");
                using (X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
                {
                    store.Open(OpenFlags.ReadWrite);
                    store.Add(cert);
                }
                Console.WriteLine("Done");
            }
        }
示例#13
0
        static void Main(string[] args)
        {
            Console.Write("distinguished-name: ");
            var distinguishedFor = Console.ReadLine();

            Console.WriteLine("Generating RSA-Keys...");

            using (var cryptContext = new CryptContext())
            {
                cryptContext.Open();

                /* Generate Certificate with default settings:
                 *
                 *  DateTime today = DateTime.Today;
                 *  ValidFrom = today.AddDays(-1);
                 *  ValidTo = today.AddYears(10);
                 *  Name = new X500DistinguishedName("cn=self");
                 *  KeyBitLength = 4096;
                 *
                 * X509Certificate2 certificate = cryptContext.CreateSelfSignedCertificate(new SelfSignedCertProperties());
                 */

                // Generate Certificate with custom setting
                X509Certificate2 certificate = cryptContext.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName("cn=" + (distinguishedFor == "" ? "localhost" : distinguishedFor)),
                    ValidFrom = DateTime.Today.AddDays(-1),
                    ValidTo   = DateTime.Today.AddYears(1)
                });

                Log.DisplaySelfCertDetails(certificate);
                Console.ReadLine();
            }
        }