コード例 #1
0
 public virtual void SaveCsrParams(CsrParams csrParams, Stream target)
 {
     using (var w = new StreamWriter(target))
     {
         w.Write(JsonConvert.SerializeObject(csrParams));
     }
 }
コード例 #2
0
        public static string GetCertificate(Target binding)
        {

            var dnsIdentifier = binding.Host;
            var SANList = binding.AlternativeNames;
            List<string> allDnsIdentifiers = new List<string>();

            if (!Options.SAN)
            {
                allDnsIdentifiers.Add(binding.Host);
            }
            if (binding.AlternativeNames != null)
            {
                allDnsIdentifiers.AddRange(binding.AlternativeNames);
            }

            var cp = CertificateProvider.GetProvider();
            var rsaPkp = new RsaPrivateKeyParams();
            try
            {
                if (Properties.Settings.Default.RSAKeyBits >= 1024)
                {
                    rsaPkp.NumBits = Properties.Settings.Default.RSAKeyBits;
                    Log.Debug("RSAKeyBits: {RSAKeyBits}", Properties.Settings.Default.RSAKeyBits);
                }
                else
                {
                    Log.Warning("RSA Key Bits less than 1024 is not secure. Letting ACMESharp default key bits. http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html");
                }
            }
            catch (Exception ex)
            {
                Log.Warning("Unable to set RSA Key Bits, Letting ACMESharp default key bits, Error: {@ex}", ex);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine($"Unable to set RSA Key Bits, Letting ACMESharp default key bits, Error: {ex.Message.ToString()}");
                Console.ResetColor();
            }

            var rsaKeys = cp.GeneratePrivateKey(rsaPkp);
            var csrDetails = new CsrDetails
            {
                CommonName = dnsIdentifier,
            };
            if(SANList != null)
            {
                if (SANList.Count > 0)
                {
                    csrDetails.AlternativeNames = SANList;
                }
            }
            var csrParams = new CsrParams
            {
                Details = csrDetails,
            };
            var csr = cp.GenerateCsr(csrParams, rsaKeys, Crt.MessageDigest.SHA256);

            byte[] derRaw;
            using (var bs = new MemoryStream())
            {
                cp.ExportCsr(csr, EncodingFormat.DER, bs);
                derRaw = bs.ToArray();
            }
            var derB64u = JwsHelper.Base64UrlEncode(derRaw);

            Console.WriteLine($"\nRequesting Certificate");
            Log.Information("Requesting Certificate");
            var certRequ = client.RequestCertificate(derB64u);

            Log.Debug("certRequ {@certRequ}", certRequ);

            Console.WriteLine($" Request Status: {certRequ.StatusCode}");
            Log.Information("Request Status: {StatusCode}", certRequ.StatusCode);

            if (certRequ.StatusCode == System.Net.HttpStatusCode.Created)
            {
                var keyGenFile = Path.Combine(certificatePath, $"{dnsIdentifier}-gen-key.json");
                var keyPemFile = Path.Combine(certificatePath, $"{dnsIdentifier}-key.pem");
                var csrGenFile = Path.Combine(certificatePath, $"{dnsIdentifier}-gen-csr.json");
                var csrPemFile = Path.Combine(certificatePath, $"{dnsIdentifier}-csr.pem");
                var crtDerFile = Path.Combine(certificatePath, $"{dnsIdentifier}-crt.der");
                var crtPemFile = Path.Combine(certificatePath, $"{dnsIdentifier}-crt.pem");
                string crtPfxFile = null;
                if (!CentralSSL)
                {
                    crtPfxFile = Path.Combine(certificatePath, $"{dnsIdentifier}-all.pfx");
                }
                else
                {
                    crtPfxFile = Path.Combine(Options.CentralSSLStore, $"{dnsIdentifier}.pfx");
                }

                using (var fs = new FileStream(keyGenFile, FileMode.Create))
                    cp.SavePrivateKey(rsaKeys, fs);
                using (var fs = new FileStream(keyPemFile, FileMode.Create))
                    cp.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);
                using (var fs = new FileStream(csrGenFile, FileMode.Create))
                    cp.SaveCsr(csr, fs);
                using (var fs = new FileStream(csrPemFile, FileMode.Create))
                    cp.ExportCsr(csr, EncodingFormat.PEM, fs);

                Console.WriteLine($" Saving Certificate to {crtDerFile}");
                Log.Information("Saving Certificate to {crtDerFile}", crtDerFile);
                using (var file = File.Create(crtDerFile))
                    certRequ.SaveCertificate(file);

                Crt crt;
                using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                        target = new FileStream(crtPemFile, FileMode.Create))
                {
                    crt = cp.ImportCertificate(EncodingFormat.DER, source);
                    cp.ExportCertificate(crt, EncodingFormat.PEM, target);
                }

                // To generate a PKCS#12 (.PFX) file, we need the issuer's public certificate
                var isuPemFile = GetIssuerCertificate(certRequ, cp);

                Log.Debug("CentralSSL {CentralSSL} SAN {SAN}", CentralSSL.ToString(), Options.SAN.ToString());

                if(CentralSSL && Options.SAN)
                {
                    foreach (var host in allDnsIdentifiers)
                    {
                        Console.WriteLine($"Host: {host}");
                        crtPfxFile = Path.Combine(Options.CentralSSLStore, $"{host}.pfx");

                        Console.WriteLine($" Saving Certificate to {crtPfxFile}");
                        Log.Information("Saving Certificate to {crtPfxFile}", crtPfxFile);
                        using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                                target = new FileStream(crtPfxFile, FileMode.Create))
                        {
                            try
                            {
                                var isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                                cp.ExportArchive(rsaKeys, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target, Properties.Settings.Default.PFXPassword);
                            }
                            catch (Exception ex)
                            {
                                Log.Error("Error exporting archive {@ex}", ex);
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine($"Error exporting archive: {ex.Message.ToString()}");
                                Console.ResetColor();
                            }
                        }
                    }
                }
                else //Central SSL and SAN need to save the cert for each hostname
                {
                    Console.WriteLine($" Saving Certificate to {crtPfxFile}");
                    Log.Information("Saving Certificate to {crtPfxFile}", crtPfxFile);
                    using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                            target = new FileStream(crtPfxFile, FileMode.Create))
                    {
                        try
                        {
                            var isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                            cp.ExportArchive(rsaKeys, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target, Properties.Settings.Default.PFXPassword);
                        }
                        catch (Exception ex)
                        {
                            Log.Error("Error exporting archive {@ex}", ex);
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine($"Error exporting archive: {ex.Message.ToString()}");
                            Console.ResetColor();
                        }
                    }
                }

                cp.Dispose();

                return crtPfxFile;
            }
            Log.Error("Request status = {StatusCode}", certRequ.StatusCode);
            throw new Exception($"Request status = {certRequ.StatusCode}");
        }
コード例 #3
0
        public void TestGenerateRsaCsr()
        {
            using (var cp = GetCP())
            {
                var pkp = new RsaPrivateKeyParams();
                var pk = cp.GeneratePrivateKey(pkp);

                var crp = new CsrParams
                {
                    Details = new CsrDetails
                    {
                        CommonName = "TEST CERT",
                    }
                };

                var csr = cp.GenerateCsr(crp, pk, Crt.MessageDigest.SHA256);
            }
        }
コード例 #4
0
        private void TestImportRsaCsr(EncodingFormat fmt)
        {
            using (var cp = CertificateProvider.GetProvider())
            {
                var pkp = new RsaPrivateKeyParams();
                var pk = cp.GeneratePrivateKey(pkp);

                var crp = new CsrParams
                {
                    Details = new CsrDetails
                    {
                        CommonName = "TEST CERT",
                    }
                };

                var csr = cp.GenerateCsr(crp, pk, Crt.MessageDigest.SHA256);
                byte[] bytes;
                using (var target = new MemoryStream())
                {
                    cp.ExportCsr(csr, fmt, target);
                    bytes = target.ToArray();
                }

                var imp = csr;
                using (var source = new MemoryStream(bytes))
                {
                    imp = cp.ImportCsr(fmt, source);
                }

                using (MemoryStream save1 = new MemoryStream(), save2 = new MemoryStream())
                {
                    cp.SaveCsr(csr, save1);
                    cp.SaveCsr(imp, save2);

                    var bytes1 = save1.ToArray();
                    var bytes2 = save2.ToArray();

                    CollectionAssert.AreEqual(bytes1, bytes2);
                }
            }
        }
コード例 #5
0
        private void TestExportRsaCsr(EncodingFormat fmt)
        {
            using (var cp = CertificateProvider.GetProvider())
            {
                var pkp = new RsaPrivateKeyParams();
                var pk = cp.GeneratePrivateKey(pkp);

                var crp = new CsrParams
                {
                    Details = new CsrDetails
                    {
                        CommonName = "TEST CERT",
                    }
                };

                var csr = cp.GenerateCsr(crp, pk, Crt.MessageDigest.SHA256);

                using (var target = new MemoryStream())
                {
                    cp.ExportCsr(csr, fmt, target);
                }
            }
        }
コード例 #6
0
        public static string GetCertificate(Target binding)
        {
            var dnsIdentifier = binding.Host;

            var cp = CertificateProvider.GetProvider();
            var rsaPkp = new RsaPrivateKeyParams();

            var rsaKeys = cp.GeneratePrivateKey(rsaPkp);
            var csrDetails = new CsrDetails
            {
                CommonName = dnsIdentifier,
            };
            var csrParams = new CsrParams
            {
                Details = csrDetails,
            };
            var csr = cp.GenerateCsr(csrParams, rsaKeys, Crt.MessageDigest.SHA256);

            byte[] derRaw;
            using (var bs = new MemoryStream())
            {
                cp.ExportCsr(csr, EncodingFormat.DER, bs);
                derRaw = bs.ToArray();
            }
            var derB64u = JwsHelper.Base64UrlEncode(derRaw);

            Console.WriteLine($"\nRequesting Certificate");
            var certRequ = client.RequestCertificate(derB64u);

            Console.WriteLine($" Request Status: {certRequ.StatusCode}");

            //Console.WriteLine($"Refreshing Cert Request");
            //client.RefreshCertificateRequest(certRequ);

            if (certRequ.StatusCode == System.Net.HttpStatusCode.Created)
            {
                var keyGenFile = Path.Combine(configPath, $"{dnsIdentifier}-gen-key.json");
                var keyPemFile = Path.Combine(configPath, $"{dnsIdentifier}-key.pem");
                var csrGenFile = Path.Combine(configPath, $"{dnsIdentifier}-gen-csr.json");
                var csrPemFile = Path.Combine(configPath, $"{dnsIdentifier}-csr.pem");
                var crtDerFile = Path.Combine(configPath, $"{dnsIdentifier}-crt.der");
                var crtPemFile = Path.Combine(configPath, $"{dnsIdentifier}-crt.pem");
                string crtPfxFile = null;
                if (!CentralSSL)
                {
                    crtPfxFile = Path.Combine(configPath, $"{dnsIdentifier}-all.pfx");
                }
                else
                {
                    crtPfxFile = Path.Combine(Options.CentralSSLStore, $"{dnsIdentifier}.pfx");
                }

                using (var fs = new FileStream(keyGenFile, FileMode.Create))
                    cp.SavePrivateKey(rsaKeys, fs);
                using (var fs = new FileStream(keyPemFile, FileMode.Create))
                    cp.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);
                using (var fs = new FileStream(csrGenFile, FileMode.Create))
                    cp.SaveCsr(csr, fs);
                using (var fs = new FileStream(csrPemFile, FileMode.Create))
                    cp.ExportCsr(csr, EncodingFormat.PEM, fs);

                Console.WriteLine($" Saving Certificate to {crtDerFile}");
                using (var file = File.Create(crtDerFile))
                    certRequ.SaveCertificate(file);

                Crt crt;
                using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                        target = new FileStream(crtPemFile, FileMode.Create))
                {
                    crt = cp.ImportCertificate(EncodingFormat.DER, source);
                    cp.ExportCertificate(crt, EncodingFormat.PEM, target);
                }

                // To generate a PKCS#12 (.PFX) file, we need the issuer's public certificate
                var isuPemFile = GetIssuerCertificate(certRequ, cp);

                Console.WriteLine($" Saving Certificate to {crtPfxFile} (with no password set)");
                using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                        target = new FileStream(crtPfxFile, FileMode.Create))
                {
                    var isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                    cp.ExportArchive(rsaKeys, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target);
                }

                cp.Dispose();

                return crtPfxFile;
            }

            throw new Exception($"Request status = {certRequ.StatusCode}");
        }
コード例 #7
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                    throw new InvalidOperationException("No registrations found");

                var ri = v.Registrations[0];
                var r = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                    throw new InvalidOperationException("No certificates found");

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                    throw new Exception("Unable to find a Certificate for the given reference");

                using (var cp = CertificateProvider.GetProvider())
                {

                    if (!string.IsNullOrEmpty(ci.GenerateDetailsFile))
                    {
                        // Generate a private key and CSR:
                        //    Key:  RSA 2048-bit
                        //    MD:   SHA 256
                        //    CSR:  Details pulled from CSR Details JSON file

                        CsrDetails csrDetails;
                        var csrDetailsAsset = vp.GetAsset(VaultAssetType.CsrDetails, ci.GenerateDetailsFile);
                        using (var s = vp.LoadAsset(csrDetailsAsset))
                        {
                            csrDetails = JsonHelper.Load<CsrDetails>(s);
                        }

                        var keyGenFile = $"{ci.Id}-gen-key.json";
                        var keyPemFile = $"{ci.Id}-key.pem";
                        var csrGenFile = $"{ci.Id}-gen-csr.json";
                        var csrPemFile = $"{ci.Id}-csr.pem";

                        var keyGenAsset = vp.CreateAsset(VaultAssetType.KeyGen, keyGenFile);
                        var keyPemAsset = vp.CreateAsset(VaultAssetType.KeyPem, keyPemFile);
                        var csrGenAsset = vp.CreateAsset(VaultAssetType.CsrGen, csrGenFile);
                        var csrPemAsset = vp.CreateAsset(VaultAssetType.CsrPem, csrPemFile);

                        var genKeyParams = new RsaPrivateKeyParams();

                        var genKey = cp.GeneratePrivateKey(genKeyParams);
                        using (var s = vp.SaveAsset(keyGenAsset))
                        {
                            cp.SavePrivateKey(genKey, s);
                        }
                        using (var s = vp.SaveAsset(keyPemAsset))
                        {
                            cp.ExportPrivateKey(genKey, EncodingFormat.PEM, s);
                        }

                        // TODO: need to surface details of the CSR params up higher
                        var csrParams = new CsrParams
                        {
                            Details = csrDetails
                        };
                        var genCsr = cp.GenerateCsr(csrParams, genKey, Crt.MessageDigest.SHA256);
                        using (var s = vp.SaveAsset(csrGenAsset))
                        {
                            cp.SaveCsr(genCsr, s);
                        }
                        using (var s = vp.SaveAsset(csrPemAsset))
                        {
                            cp.ExportCsr(genCsr, EncodingFormat.PEM, s);
                        }

                        ci.KeyPemFile = keyPemFile;
                        ci.CsrPemFile = csrPemFile;
                    }



                    byte[] derRaw;

                    var asset = vp.GetAsset(VaultAssetType.CsrPem, ci.CsrPemFile);
                    // Convert the stored CSR in PEM format to DER
                    using (var source = vp.LoadAsset(asset))
                    {
                        var csr = cp.ImportCsr(EncodingFormat.PEM, source);
                        using (var target = new MemoryStream())
                        {
                            cp.ExportCsr(csr, EncodingFormat.DER, target);
                            derRaw = target.ToArray();
                        }
                    }

                    var derB64u = JwsHelper.Base64UrlEncode(derRaw);

                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        ci.CertificateRequest = c.RequestCertificate(derB64u);
                    }

                    if (!string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                    {
                        var crtDerFile = $"{ci.Id}-crt.der";
                        var crtPemFile = $"{ci.Id}-crt.pem";

                        var crtDerBytes = ci.CertificateRequest.GetCertificateContent();

                        var crtDerAsset = vp.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                        var crtPemAsset = vp.CreateAsset(VaultAssetType.CrtPem, crtPemFile);

                        using (Stream source = new MemoryStream(crtDerBytes),
                                derTarget = vp.SaveAsset(crtDerAsset),
                                pemTarget = vp.SaveAsset(crtPemAsset))
                        {
                            var crt = cp.ImportCertificate(EncodingFormat.DER, source);

                            cp.ExportCertificate(crt, EncodingFormat.DER, derTarget);
                            ci.CrtDerFile = crtDerFile;

                            cp.ExportCertificate(crt, EncodingFormat.PEM, pemTarget);
                            ci.CrtPemFile = crtPemFile;
                        }

                        // Extract a few pieces of info from the issued
                        // cert that we like to have quick access to
                        var x509 = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                        ci.SerialNumber = x509.SerialNumber;
                        ci.Thumbprint = x509.Thumbprint;
                        ci.SignatureAlgorithm = x509.SignatureAlgorithm?.FriendlyName;
                        ci.Signature = x509.GetCertHashString();
                    }
                }

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
コード例 #8
0
        public void Test0170_GenCsrAndRequestCertificate()
        {
            using (var cp = CertificateProvider.GetProvider())
            {

                var rsaKeyParams = new RsaPrivateKeyParams();
                var rsaKey = cp.GeneratePrivateKey(rsaKeyParams);

                _testGenCsr_RsaKeysFile = $"{_baseLocalStore}\\TestGenCsr-rsaKeys.txt";
                using (var fs = new FileStream(_testGenCsr_RsaKeysFile, FileMode.Create))
                {
                    cp.SavePrivateKey(rsaKey, fs);
                }

                var csrParams = new CsrParams
                {
                    Details = new CsrDetails
                    {
                        CommonName = TEST_CN1
                    }
                };

                var csr = cp.GenerateCsr(csrParams, rsaKey, Crt.MessageDigest.SHA256);
                _testGenCsr_CsrDetailsFile = $"{_baseLocalStore}\\TestGenCsr-csrDetails.txt";
                using (var fs = new FileStream(_testGenCsr_CsrDetailsFile, FileMode.Create))
                {
                    cp.SaveCsrParams(csrParams, fs);
                }
                _testGenCsr_CsrFile = $"{_baseLocalStore}\\TestGenCsr-csr.txt";
                using (var fs = new FileStream(_testGenCsr_CsrFile, FileMode.Create))
                {
                    cp.SaveCsr(csr, fs);
                }

                using (var signer = new RS256Signer())
                {
                    signer.Init();
                    using (var fs = new FileStream(_testRegister_AcmeSignerFile, FileMode.Open))
                    {
                        signer.Load(fs);
                    }

                    AcmeRegistration reg;
                    using (var fs = new FileStream(_testRegister_AcmeRegFile, FileMode.Open))
                    {
                        reg = AcmeRegistration.Load(fs);
                    }

                    byte[] derRaw;
                    using (var bs = new MemoryStream())
                    {
                        cp.ExportCsr(csr, EncodingFormat.DER, bs);
                        derRaw = bs.ToArray();
                    }
                    var derB64u = JwsHelper.Base64UrlEncode(derRaw);

                    using (var client = BuildClient(testTagHeader: nameof(Test0170_GenCsrAndRequestCertificate)))
                    {
                        client.RootUrl = _rootUrl;
                        client.Signer = signer;
                        client.Registration = reg;
                        client.Init();

                        client.GetDirectory(true);

                        var certRequ = client.RequestCertificate(derB64u);

                        _testCertRequ_AcmeCertRequFile = $"{_baseLocalStore}\\TestCertRequ.acmeCertRequ";
                        using (var fs = new FileStream(_testCertRequ_AcmeCertRequFile, FileMode.Create))
                        {
                            certRequ.Save(fs);
                        }
                    }
                }
            }
        }
コード例 #9
0
 public abstract Csr GenerateCsr(CsrParams csrParams, PrivateKey pk, Crt.MessageDigest md);