Ejemplo n.º 1
0
        public void TestListNotes()
        {
            var orderId = "123";

            using (var server = new HttpServer(new RequestHandler
            {
                EstimatedMethod = "GET",
                EstimatedPathAndQuery = $"/v1.0/accounts/{Helper.AccountId}/csrs/{orderId}/notes",
                ContentToSend = new StringContent(TestXmlStrings.notesResponse2, Encoding.UTF8, "application/xml")
            }))
            {
                var client = Helper.CreateClient();
                var result = Csr.ListNotes(client, orderId).Result;
                if (server.Error != null)
                {
                    throw server.Error;
                }

                Assert.IsNotNull(result.List);

                Assert.AreEqual(result.List.Length, 2);

                Assert.AreEqual(result.List[0].Description, "This is a test note");
                Assert.AreEqual(result.List[0].Id, "87037");
                Assert.AreEqual(result.List[0].UserId, "jbm");
                Assert.AreEqual(result.List[0].LastDateModifier, DateTime.Parse("2014-11-16T04:01:10.000"));
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Default implementation of saving a private key serializes as a JSON object.
 /// </summary>
 public virtual void SaveCsr(Csr csr, Stream target)
 {
     using (var w = new StreamWriter(target))
     {
         w.Write(JsonConvert.SerializeObject(csr));
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Default implementation of saving a private key serializes as a JSON object.
 /// </summary>
 public virtual void SaveCsr(Csr csr, Stream target)
 {
     using (var w = new StreamWriter(target))
     {
         w.Write(JsonConvert.SerializeObject(csr));
     }
 }
Ejemplo n.º 4
0
        public override void ExportCsr(Csr csr, EncodingFormat fmt, Stream target)
        {
            string outform;

            switch (fmt)
            {
            case EncodingFormat.PEM:
                outform = "PEM";
                break;

            case EncodingFormat.DER:
                outform = "DER";
                break;

            default:
                throw new NotSupportedException("unsupported encoding format");
            }

            var tempSource = Path.GetTempFileName();
            var tempTarget = Path.GetTempFileName();

            try
            {
                File.WriteAllText(tempSource, csr.Pem);
                RunCli($"req -inform PEM -in {tempSource} -outform {outform} -out {tempTarget}");
                var targetBytes = File.ReadAllBytes(tempTarget);
                target.Write(targetBytes, 0, targetBytes.Length);
            }
            finally
            {
                File.Delete(tempSource);
                File.Delete(tempTarget);
            }
        }
Ejemplo n.º 5
0
        public void Regular()
        {
            var tempFile = Path.GetTempFileName();

            try
            {
                File.WriteAllText(tempFile, Csr);
                var csrOptions = new CsrOptions()
                {
                    CsrFile = tempFile
                };
                var log       = new Mock.Services.LogService(false);
                var pem       = new PemService();
                var csrPlugin = new Csr(log, pem, csrOptions);
                var target    = csrPlugin.Generate().Result;
                Assert.IsNotNull(target);
                Assert.IsFalse(target is INull);
                Assert.IsTrue(target.Parts.Count() == 1);
                Assert.IsTrue(target.Parts.First().Identifiers.OfType <IpIdentifier>().Count() == 3);
                Assert.IsTrue(target.Parts.First().Identifiers.OfType <DnsIdentifier>().Count() == 2);
                Assert.IsTrue(target.Parts.First().Identifiers.OfType <EmailIdentifier>().Count() == 1);
                Assert.IsTrue(target.Parts.First().Identifiers.OfType <IpIdentifier>().Any(x => x.Value == "1.1.1.1"));
                Assert.IsTrue(target.Parts.First().Identifiers.OfType <DnsIdentifier>().Any(x => x.Value == "www.win-acme.com"));
                Assert.IsTrue(target.Parts.First().Identifiers.OfType <EmailIdentifier>().Any(x => x.Value == "*****@*****.**"));
            }
            finally
            {
                File.Delete(tempFile);
            }
        }
Ejemplo n.º 6
0
        public void TryGenerateCSRCustomOID()
        {
            int      rc;
            KeyBlob  keyBlob  = new KeyBlob();
            Template template = new Template();
            Csr      csr      = new Csr();

            byte[] output = new byte[Device.MAX_TPM_BUFFER];

            string subject = "/C=US/ST=Oregon/L=Portland/SN=Development" +
                             "/O=wolfSSL/OU=RSA/CN=www.wolfssl.com" +
                             "/[email protected]";
            string keyUsage = "serverAuth,clientAuth,codeSigning";

            string custOid    = "1.2.3.4.5";
            string custOidVal = "This is NOT a critical extension";

            Console.WriteLine("Testing generate CSR custom");

            rc = template.GetKeyTemplate_RSA((ulong)(
                                                 TPM2_Object.sensitiveDataOrigin |
                                                 TPM2_Object.userWithAuth |
                                                 TPM2_Object.decrypt |
                                                 TPM2_Object.sign |
                                                 TPM2_Object.noDA));
            Assert.AreEqual((int)Status.TPM_RC_SUCCESS, rc);

            rc = device.CreateKey(keyBlob, parent_key, template,
                                  "ThisIsMyStorageKeyAuth");
            Assert.AreEqual((int)Status.TPM_RC_SUCCESS, rc);

            rc = device.LoadKey(keyBlob, parent_key);
            Assert.AreEqual((int)Status.TPM_RC_SUCCESS, rc);

            rc = csr.SetSubject(subject);
            Assert.AreEqual((int)Status.TPM_RC_SUCCESS, rc);

            rc = csr.SetKeyUsage(keyUsage);
            Assert.AreEqual((int)Status.TPM_RC_SUCCESS, rc);

            rc = csr.SetCustomExtension(custOid, custOidVal, 0);

            /* if custom OID support is not compiled in then test is
             * inconclusive */
            if (rc == (int)Status.NOT_COMPILED_IN)
            {
                device.UnloadHandle(keyBlob);
                Assert.Inconclusive();
            }
            Assert.AreEqual((int)Status.TPM_RC_SUCCESS, rc);

            rc = csr.MakeAndSign(device, keyBlob, X509_Format.PEM, output);
            Assert.That(rc, Is.GreaterThan(0));

            Console.WriteLine("CSR PEM {0} bytes", rc.ToString());

            rc = device.UnloadHandle(keyBlob);
            Assert.AreEqual((int)Status.TPM_RC_SUCCESS, rc);
        }
Ejemplo n.º 7
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ (Csr?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (HighestCsr?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ MeasurementMatchesLeft;
         hashCode = (hashCode * 397) ^ PlaylistId.GetHashCode();
         return(hashCode);
     }
 }
Ejemplo n.º 8
0
        public void TestReplace()
        {
            var orderId = "123";

            var csr = new Csr
            {
            };

            using (var server = new HttpServer(new RequestHandler
            {
                EstimatedMethod = "PUT",
                EstimatedPathAndQuery = $"/v1.0/accounts/{Helper.AccountId}/csrs/{orderId}",
                ContentToSend = new StringContent(TestXmlStrings.csrResponse, Encoding.UTF8, "application/xml")
            }))
            {
                var client = Helper.CreateClient();
                var result = Csr.Replace(client, orderId, csr).Result;
                if (server.Error != null)
                {
                    throw server.Error;
                }

                Assert.AreEqual(result.CustomerOrderId, "TEST BWDB-6506");
                Assert.AreEqual(result.LastModifiedBy, "systemUser");
                Assert.AreEqual(result.OrderCreateDate, "2020-01-13T21:14:35Z");
                Assert.AreEqual(result.AccountId, "14");
                Assert.AreEqual(result.OrderId, "5c3b8240-52b5-45a5-8d7d-42a71ebcd1ba");
                Assert.AreEqual(result.LastModifiedDate, "2020-01-13T16:51:21.920Z");
                Assert.AreEqual(result.Status, "COMPLETE");
                Assert.AreEqual(result.AccountNumber, "987654321");
                Assert.AreEqual(result.AccountTelephoneNumber, "9196194444");
                Assert.AreEqual(result.EndUserName, "bandwidthGuy");
                Assert.AreEqual(result.AuthorizingUserName, "importantAuthGuy");
                Assert.AreEqual(result.CustomerCode, "123");
                Assert.AreEqual(result.EndUserPIN, "12345");
                Assert.AreEqual(result.EndUserPassword, "enduserpassword123");
                Assert.AreEqual(result.AddressLine1, "900 Main Campus Dr");
                Assert.AreEqual(result.City, "Raleigh");
                Assert.AreEqual(result.State, "NC");
                Assert.AreEqual(result.ZIPCode, "27612");
                Assert.AreEqual(result.TypeOfService, "residential");
                Assert.AreEqual(result.CsrData.AccountNumber, "123456789");
                Assert.AreEqual(result.CsrData.CustomerName, "JOHN SMITH");
                Assert.AreEqual(result.CsrData.WorkingTelephoneNumber, "9196191156");
                Assert.AreEqual(result.CsrData.WorkingTelephoneNumbersOnAccount.Length, 1);
                Assert.AreEqual(result.CsrData.WorkingTelephoneNumbersOnAccount[0], "9196191156");

                Assert.IsNotNull(result.CsrData.ServiceAddress);
            }
        }
        public override void ExportCsr(Csr csr, EncodingFormat fmt, Stream target)
        {
            string outform;

            switch (fmt)
            {
            case EncodingFormat.PEM:
                outform = "PEM";
                break;

            case EncodingFormat.DER:
                outform = "DER";
                break;

            default:
                throw new NotSupportedException("unsupported encoding format");
            }

            var ceReq = new CERTENROLLLib.CX509CertificateRequestCertificate();

            ceReq.InitializeDecode(csr.Pem);

            if (fmt == EncodingFormat.DER)
            {
                var bytes = EncodeRaw(ceReq.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BINARY]);
                target.Write(bytes, 0, bytes.Length);
            }
            else if (fmt == EncodingFormat.PEM)
            {
                var ceCsr = new CERTENROLLLib.CX509Enrollment();
                ceCsr.InitializeFromRequest(ceReq);
                var pem = ceCsr.CreateRequest(
                    CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER);
                var bytes = Encoding.UTF8.GetBytes(pem);
                target.Write(bytes, 0, bytes.Length);
            }
            else
            {
                throw new NotSupportedException("unsupported encoding format");
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Support exporting CSR to <see cref="EncodingFormat.PEM">PEM</see>
 /// and <see cref="EncodingFormat.DER">DER</see> formats.
 /// </summary>
 public override void ExportCsr(Csr csr, EncodingFormat fmt, Stream target)
 {
     if (fmt == EncodingFormat.PEM)
     {
         var bytes = Encoding.UTF8.GetBytes(csr.Pem);
         target.Write(bytes, 0, bytes.Length);
     }
     else if (fmt == EncodingFormat.DER)
     {
         using (var tr = new StringReader(csr.Pem))
         {
             PemReader pr       = new PemReader(tr);
             var       bcCsr    = (Pkcs10CertificationRequest)pr.ReadObject();
             var       derBytes = bcCsr.GetDerEncoded();
             target.Write(derBytes, 0, derBytes.Length);
         }
     }
     else
     {
         throw new NotSupportedException("encoding format has not been implemented");
     }
 }
Ejemplo n.º 11
0
        public override Csr ImportCsr(EncodingFormat fmt, Stream source)
        {
            string inform;

            switch (fmt)
            {
            case EncodingFormat.PEM:
                inform = "PEM";
                break;

            case EncodingFormat.DER:
                inform = "DER";
                break;

            default:
                throw new NotSupportedException("unsupported encoding format");
            }

            var tempSource = Path.GetTempFileName();
            var tempTarget = Path.GetTempFileName();

            try
            {
                using (var fs = new FileStream(tempSource, FileMode.Create))
                {
                    source.CopyTo(fs);
                }

                RunCli($"req -inform {inform} -in {tempSource} -outform PEM -out {tempTarget}");
                var csr = new Csr(File.ReadAllText(tempTarget));
                return(csr);
            }
            finally
            {
                File.Delete(tempSource);
                File.Delete(tempTarget);
            }
        }
Ejemplo n.º 12
0
        public void TestUpdateNote()
        {
            var orderId = "123";
            var noteId  = "note123";

            var note = new Note
            {
            };

            using (var server = new HttpServer(new RequestHandler
            {
                EstimatedMethod = "PUT",
                EstimatedPathAndQuery = $"/v1.0/accounts/{Helper.AccountId}/csrs/{orderId}/notes/{noteId}",
            }))
            {
                var client = Helper.CreateClient();
                Csr.UpdateNote(client, orderId, noteId, note).Wait();
                if (server.Error != null)
                {
                    throw server.Error;
                }
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Support exporting CSR to <see cref="EncodingFormat.PEM">PEM</see>
 /// and <see cref="EncodingFormat.DER">DER</see> formats.
 /// </summary>
 public override void ExportCsr(Csr csr, EncodingFormat fmt, Stream target)
 {
     if (fmt == EncodingFormat.PEM)
     {
         var bytes = Encoding.UTF8.GetBytes(csr.Pem);
         target.Write(bytes, 0, bytes.Length);
     }
     else if (fmt == EncodingFormat.DER)
     {
         using (var xr = new X509Request(csr.Pem))
         {
             using (var bio = BIO.MemoryBuffer())
             {
                 xr.Write_DER(bio);
                 var arr = bio.ReadBytes((int)bio.BytesPending);
                 target.Write(arr.Array, arr.Offset, arr.Count);
             }
         }
     }
     else
     {
         throw new NotSupportedException("encoding format has not been implemented");
     }
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Support importing CSR from <see cref="EncodingFormat.PEM">PEM</see>
 /// and <see cref="EncodingFormat.DER">DER</see> formats.
 /// </summary>
 public override Csr ImportCsr(EncodingFormat fmt, Stream source)
 {
     if (fmt == EncodingFormat.PEM)
     {
         using (var r = new StreamReader(source))
         {
             using (var x509 = new X509Request(r.ReadToEnd()))
             {
                 var csr = new Csr(x509.PEM);
                 return(csr);
             }
         }
     }
     else if (fmt == EncodingFormat.DER)
     {
         // TODO: Managed OpenSSL Library has not implemented
         // d2i_X509_REQ_bio(...) routine yet
         throw new NotImplementedException("x509 CSR export to DER has not yet been implemented");
     }
     else
     {
         throw new NotSupportedException("unsupported encoding format");
     }
 }
Ejemplo n.º 15
0
        static void GenerateCertFiles(CertificateProvider provider, PrivateKey rsaKeys,
                                      Csr csr, CertificateRequest request, string certificatesFolder, string domain)
        {
            var crt = default(Crt);


            var keyGenFile = Path.Combine(certificatesFolder, $"{domain}-gen-key.json");

            Log.Debug($"Gerando arquivo: {keyGenFile}");
            using (var fs = new FileStream(keyGenFile, FileMode.Create))
                provider.SavePrivateKey(rsaKeys, fs);

            var keyPemFile = Path.Combine(certificatesFolder, $"{domain}-key.pem");

            Log.Debug($"Gerando arquivo: {keyPemFile}");
            using (var fs = new FileStream(keyPemFile, FileMode.Create))
                provider.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);

            var csrGenFile = Path.Combine(certificatesFolder, $"{domain}-gen-csr.json");

            Log.Debug($"Gerando arquivo: {csrGenFile}");
            using (var fs = new FileStream(csrGenFile, FileMode.Create))
                provider.SaveCsr(csr, fs);

            var csrPemFile = Path.Combine(certificatesFolder, $"{domain}-csr.pem");

            Log.Debug($"Gerando arquivo: {csrPemFile}");
            using (var fs = new FileStream(csrPemFile, FileMode.Create))
                provider.ExportCsr(csr, EncodingFormat.PEM, fs);

            var crtDerFile = Path.Combine(certificatesFolder, $"{domain}-crt.der");

            Log.Debug($"Gerando arquivo: {crtDerFile}");
            using (var file = File.Create(crtDerFile))
                request.SaveCertificate(file);

            var crtPemFile   = Path.Combine(certificatesFolder, $"{domain}-crt.pem");
            var chainPemFile = Path.Combine(certificatesFolder, $"{domain}-chain.pem");

            Log.Debug($"Gerando arquivo: {crtPemFile}");
            Log.Debug($"Gerando arquivo: {chainPemFile}");
            using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                   target = new FileStream(crtPemFile, FileMode.Create))
            {
                crt = provider.ImportCertificate(EncodingFormat.DER, source);
                provider.ExportCertificate(crt, EncodingFormat.PEM, target);
            }

            var pemFile = DownloadIssuerCertificate(provider, request, ACME_API, certificatesFolder);

            using (FileStream intermediate = new FileStream(pemFile, FileMode.Open),
                   certificate = new FileStream(crtPemFile, FileMode.Open),
                   chain = new FileStream(chainPemFile, FileMode.Create))
            {
                certificate.CopyTo(chain);
                intermediate.CopyTo(chain);
            }

            var crtPfxFile = Path.Combine(certificatesFolder, $"{domain}-all.pfx");

            Log.Debug($"Gerando arquivo: {crtPfxFile}");
            using (FileStream source = new FileStream(pemFile, FileMode.Open),
                   target = new FileStream(crtPfxFile, FileMode.Create))
            {
                try
                {
                    var isuCrt = provider.ImportCertificate(EncodingFormat.PEM, source);
                    provider.ExportArchive(rsaKeys, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target, string.Empty);
                }
                catch (Exception ex)
                {
                    Log.Error($"Erro ao exportar o arquivo {crtPfxFile}", ex);
                }
            }
        }
 /// <summary>
 /// Creates or modifies an existing certificate signing request.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of the resource group
 /// </param>
 /// <param name='name'>
 /// Name of the certificate.
 /// </param>
 /// <param name='csrEnvelope'>
 /// Details of certificate signing request if it exists already.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <Csr> UpdateCsrAsync(this ICertificatesOperations operations, string resourceGroupName, string name, Csr csrEnvelope, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.UpdateCsrWithHttpMessagesAsync(resourceGroupName, name, csrEnvelope, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
        private void GetCertificate()
        {
            Log.Information("Requesting Certificate");

            using (CertificateProvider cp = CertificateProvider.GetProvider())
            {
                RsaPrivateKeyParams rsaPkp = new RsaPrivateKeyParams();

                PrivateKey rsaKeys   = cp.GeneratePrivateKey(rsaPkp);
                CsrParams  csrParams = new CsrParams
                {
                    Details = new CsrDetails
                    {
                        CommonName = _options.HostName,
                    },
                };

                Csr csr = cp.GenerateCsr(csrParams, rsaKeys, Crt.MessageDigest.SHA256);

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

                CertificateRequest certReq = _acmeClient.RequestCertificate(derB64U);

                if (certReq.StatusCode != HttpStatusCode.Created)
                {
                    throw new Exception($"Request status = {certReq.StatusCode}");
                }

                using (FileStream fs = new FileStream(_options.WellKnownFilePaths[WellKnownFile.KeyGen], FileMode.Create))
                    cp.SavePrivateKey(rsaKeys, fs);
                using (FileStream fs = new FileStream(_options.WellKnownFilePaths[WellKnownFile.KeyPem], FileMode.Create))
                    cp.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);
                using (FileStream fs = new FileStream(_options.WellKnownFilePaths[WellKnownFile.CsrGen], FileMode.Create))
                    cp.SaveCsr(csr, fs);
                using (FileStream fs = new FileStream(_options.WellKnownFilePaths[WellKnownFile.CsrPem], FileMode.Create))
                    cp.ExportCsr(csr, EncodingFormat.PEM, fs);

                Log.Information($"Saving Certificate to {_options.WellKnownFilePaths[WellKnownFile.CrtDer]}");
                using (FileStream file = File.Create(_options.WellKnownFilePaths[WellKnownFile.CrtDer]))
                    certReq.SaveCertificate(file);

                Crt crt;
                using (FileStream source = new FileStream(_options.WellKnownFilePaths[WellKnownFile.CrtDer], FileMode.Open),
                       target = new FileStream(_options.WellKnownFilePaths[WellKnownFile.CrtPem], 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
                string isuPemFile = GetIssuerCertificate(certReq, cp);

                using (FileStream intermediate = new FileStream(isuPemFile, FileMode.Open),
                       certificate = new FileStream(_options.WellKnownFilePaths[WellKnownFile.CrtPem], FileMode.Open),
                       chain = new FileStream(_options.WellKnownFilePaths[WellKnownFile.ChainPem], FileMode.Create))
                {
                    certificate.CopyTo(chain);
                    intermediate.CopyTo(chain);
                }

                Log.Information($"Saving Certificate to {_options.WellKnownFilePaths[WellKnownFile.CrtPfx]}");
                using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                       target = new FileStream(_options.WellKnownFilePaths[WellKnownFile.CrtPfx], FileMode.Create))
                {
                    Crt isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                    cp.ExportArchive(rsaKeys, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target, _options.PfxPassword);
                }
            }
        }
Ejemplo n.º 18
0
 public int Service_CsrSave(Csr csr)
 {
     return(DataAccess.Service.ServiceBook.Service_CsrSave(csr));
 }
        public override Csr GenerateCsr(CsrParams csrParams, PrivateKey pk, Crt.MessageDigest md)
        {
            var rsaPk = pk as CeRsaPrivateKey;

            if (rsaPk != null)
            {
                var cePk = new CERTENROLLLib.CX509PrivateKey();

                // MS_DEF_PROV
                //cePk.ProviderName = "Microsoft Base Cryptographic Provider";
                cePk.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0";

                // Don't store in the machine's local cert store and allow exporting of private key
                cePk.MachineContext = false;
                cePk.ExportPolicy   = CERTENROLLLib.X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;

                cePk.Import(BCRYPT_PRIVATE_KEY_BLOB, rsaPk.Exported);

                var ceReq = new CERTENROLLLib.CX509CertificateRequestCertificate();
                ceReq.InitializeFromPrivateKey(
                    CERTENROLLLib.X509CertificateEnrollmentContext.ContextUser,
                    cePk, "");

                // CN=Test Cert, OU=Sandbox
                var subjParts = new[]
                {
                    new { name = "C", value = csrParams?.Details?.Country },
                    new { name = "ST", value = csrParams?.Details?.StateOrProvince },
                    new { name = "L", value = csrParams?.Details?.Locality },
                    new { name = "O", value = csrParams?.Details?.Organization },
                    new { name = "OU", value = csrParams?.Details?.OrganizationUnit },
                    new { name = "CN", value = csrParams?.Details?.CommonName },
                    new { name = "E", value = csrParams?.Details?.Email },
                };

                // Escape any non-standard character
                var re   = new Regex("[^A-Za-z0-9\\._-]");
                var subj = "";
                foreach (var sp in subjParts)
                {
                    if (!string.IsNullOrEmpty(sp.value))
                    {
                        var spVal = re.Replace(sp.value, "\\$0");
                        subj += $",{sp.name}={spVal}";
                    }
                }
                if (string.IsNullOrEmpty(subj))
                {
                    throw new InvalidOperationException("invalid CSR details");
                }
                subj = subj.Substring(1); // Skip over the first comma

                // http://msdn.microsoft.com/en-us/library/aa377051(VS.85).aspx
                var subjDN = new CERTENROLLLib.CX500DistinguishedName();
                subjDN.Encode(subj);
                ceReq.Subject = subjDN;

                if (csrParams.NotBefore != null)
                {
                    ceReq.NotBefore = csrParams.NotBefore.Value;
                }
                if (csrParams.NotAfter != null)
                {
                    ceReq.NotAfter = csrParams.NotAfter.Value;
                }

                var mdVal = Enum.GetName(typeof(Crt.MessageDigest), md);
                var mdOid = new System.Security.Cryptography.Oid(mdVal);
                var mdAlg = new CERTENROLLLib.CObjectId();
                mdAlg.InitializeFromValue(mdOid.Value);
                ceReq.SignatureInformation.HashAlgorithm = mdAlg;
                ceReq.Encode();

                var csr = new Csr(ceReq.RawData);
                return(csr);
            }
            else
            {
                throw new NotSupportedException("unsuppored private key type");
            }
        }
 /// <summary>
 /// Creates or modifies an existing certificate signing request.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of the resource group
 /// </param>
 /// <param name='name'>
 /// Name of the certificate.
 /// </param>
 /// <param name='csrEnvelope'>
 /// Details of certificate signing request if it exists already.
 /// </param>
 public static Csr UpdateCsr(this ICertificatesOperations operations, string resourceGroupName, string name, Csr csrEnvelope)
 {
     return(Task.Factory.StartNew(s => ((ICertificatesOperations)s).UpdateCsrAsync(resourceGroupName, name, csrEnvelope), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Ejemplo n.º 21
0
 public override void ExportCsr(Csr csr, EncodingFormat fmt, Stream target)
 {
     _cp.ExportCsr(csr, fmt, target);
 }
Ejemplo n.º 22
0
        public override Csr GenerateCsr(CsrParams csrParams, PrivateKey pk, Crt.MessageDigest md)
        {
            var rsaPk = pk as RsaPrivateKey;

            if (rsaPk != null)
            {
                var tempCfgFile = Path.GetTempFileName();
                var tempKeyFile = Path.GetTempFileName();
                var tempCsrFile = Path.GetTempFileName();

                try
                {
                    var mdVal = Enum.GetName(typeof(Crt.MessageDigest), md);

                    var args = $"req -batch -new -keyform PEM -key {tempKeyFile} -{mdVal}";
                    args += $" -config {tempCfgFile} -outform PEM -out {tempCsrFile} -subj \"";

                    var subjParts = new[]
                    {
                        new { name = "C", value = csrParams?.Details?.Country },
                        new { name = "ST", value = csrParams?.Details?.StateOrProvince },
                        new { name = "L", value = csrParams?.Details?.Locality },
                        new { name = "O", value = csrParams?.Details?.Organization },
                        new { name = "OU", value = csrParams?.Details?.OrganizationUnit },
                        new { name = "CN", value = csrParams?.Details?.CommonName },
                        new { name = "emailAddress", value = csrParams?.Details?.Email },
                    };

                    // Escape any non-standard character
                    var re = new Regex("[^A-Za-z0-9\\._-]");
                    foreach (var sp in subjParts)
                    {
                        if (!string.IsNullOrEmpty(sp.value))
                        {
                            var spVal = re.Replace(sp.value, "\\$0");
                            args += $"/{sp.name}={spVal}";
                        }
                    }
                    args += "\"";

                    File.WriteAllText(tempKeyFile, rsaPk.Pem);
                    using (Stream source = Assembly.GetExecutingAssembly()
                                           .GetManifestResourceStream(typeof(OpenSslCliProvider),
                                                                      "OpenSslCliProvider_Config.txt"),
                           target = new FileStream(tempCfgFile, FileMode.Create))
                    {
                        source.CopyTo(target);
                    }

                    RunCli(args);
                    var csr = new Csr(File.ReadAllText(tempCsrFile));
                    return(csr);
                }
                finally
                {
                    File.Delete(tempCfgFile);
                    File.Delete(tempKeyFile);
                    File.Delete(tempCsrFile);
                }
            }

            throw new NotSupportedException("unsupported private key type");
        }