示例#1
0
    public static X509Certificate2 CreateTestCert(string[] domainNames, DateTimeOffset?expires = null)
    {
        expires ??= DateTimeOffset.Now.AddMinutes(10);
        var key = RSA.Create(2048);
        var csr = new CertificateRequest(
            "CN=" + domainNames[0],
            key,
            HashAlgorithmName.SHA512,
            RSASignaturePadding.Pkcs1);

        if (domainNames.Length > 1)
        {
            var sanBuilder = new SubjectAlternativeNameBuilder();
            foreach (var san in domainNames.Skip(1))
            {
                sanBuilder.AddDnsName(san);
            }

            csr.CertificateExtensions.Add(sanBuilder.Build());
        }

        var cert = csr.CreateSelfSigned(DateTimeOffset.Now.AddMinutes(-1), expires.Value);

        // https://github.com/dotnet/runtime/issues/29144
        return(new X509Certificate2(cert.Export(X509ContentType.Pfx), "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
    }
示例#2
0
        public void AddSubjectAlternativeName(CertificateRequest request, SubjectAlternativeName subjectAlternativeName)
        {
            foreach (var dnsName in subjectAlternativeName.DnsName)
            {
                if (UriHostNameType.Unknown == Uri.CheckHostName(dnsName))
                {
                    throw new ArgumentException("Must be a valid DNS name", nameof(dnsName));
                }
            }

            var sanBuilder = new SubjectAlternativeNameBuilder();

            foreach (var dnsName in subjectAlternativeName.DnsName)
            {
                sanBuilder.AddDnsName(dnsName);
            }

            if (!string.IsNullOrEmpty(subjectAlternativeName.Email))
            {
                sanBuilder.AddEmailAddress(subjectAlternativeName.Email);
            }

            var sanExtension = sanBuilder.Build();

            request.CertificateExtensions.Add(sanExtension);
        }
示例#3
0
        public async Task <(byte[] Cert, RSA PrivateKey)> GetCertificate(CancellationToken token = default(CancellationToken))
        {
            var key = new RSACryptoServiceProvider(4096);
            var csr = new CertificateRequest("CN=" + _hosts[0],
                                             key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            var san = new SubjectAlternativeNameBuilder();

            foreach (var host in _hosts)
            {
                san.AddDnsName(host);
            }

            csr.CertificateExtensions.Add(san.Build());
            var certResponse = await _client.NewCertificateRequestAsync(csr.CreateSigningRequest(), token);

            _cache.CachedCerts[_hosts[0]] = new CertificateCache
            {
                Cert    = certResponse.Certificate,
                Private = key.ExportCspBlob(true)
            };

            lock (Locker)
            {
                File.WriteAllText(_path,
                                  JsonConvert.SerializeObject(_cache, Formatting.Indented));
            }

            return(certResponse.Certificate, key);
        }
示例#4
0
        private static X509Certificate2 Create()
        {
            var sanBuilder = new SubjectAlternativeNameBuilder();

            sanBuilder.AddIpAddress(IPAddress.Loopback);
            sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
            sanBuilder.AddDnsName("localhost");
            sanBuilder.AddDnsName("127.0.0.1");
            sanBuilder.AddDnsName(Environment.MachineName);

            var distinguishedName = new X500DistinguishedName($"CN={CertificateName}");

            using var rsa = RSA.Create(2048);
            var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            request.CertificateExtensions.Add(
                new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));

            request.CertificateExtensions.Add(
                new X509EnhancedKeyUsageExtension(
                    new OidCollection {
                new Oid(OidServerAuthentication)
            }, false));

            request.CertificateExtensions.Add(sanBuilder.Build());

            X509Certificate2 certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddYears(100)));

            certificate.FriendlyName = CertificateName;

            return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, CertificatePass), CertificatePass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable));
        }
示例#5
0
        static X509Certificate2 GenerateCertificate(DateTime?notBefore = null, DateTime?notAfter = null, bool addServerAuthentication = true, bool addClientAuthentication = true)
        {
            var name    = Guid.NewGuid().ToString("N");
            var builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName(name);

            var dn = new X500DistinguishedName($"CN={name}");

            using (var rsa = RSA.Create(2048))
            {
                var request = new CertificateRequest(dn, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                var usage = new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyAgreement, true);
                request.CertificateExtensions.Add(usage);

                var oids = new OidCollection();
                if (addServerAuthentication)
                {
                    oids.Add(new Oid("1.3.6.1.5.5.7.3.1"));
                }
                if (addClientAuthentication)
                {
                    oids.Add(new Oid("1.3.6.1.5.5.7.3.2"));
                }

                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(oids, false));

                request.CertificateExtensions.Add(builder.Build());

                return(request.CreateSelfSigned(new DateTimeOffset(notBefore ?? DateTime.UtcNow.AddMinutes(-5)), new DateTimeOffset(notAfter ?? DateTime.UtcNow.AddMinutes(5))));
            }
        }
示例#6
0
        internal static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string targetName, [CallerMemberName] string?testName = null, bool longChain = false, bool serverCertificate = true)
        {
            const int keySize = 2048;

            if (PlatformDetection.IsWindows && testName != null)
            {
                CleanupCertificates(testName);
            }

            X509Certificate2Collection chain      = new X509Certificate2Collection();
            X509ExtensionCollection    extensions = new X509ExtensionCollection();

            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName(targetName);
            extensions.Add(builder.Build());
            extensions.Add(s_eeConstraints);
            extensions.Add(s_eeKeyUsage);
            extensions.Add(serverCertificate ? s_tlsServerEku : s_tlsClientEku);

            CertificateAuthority.BuildPrivatePki(
                PkiOptions.IssuerRevocationViaCrl,
                out RevocationResponder responder,
                out CertificateAuthority root,
                out CertificateAuthority[] intermediates,
示例#7
0
        public static X509Certificate2 BuildSelfSignedCertificate(string dns, string ipaddr, string issuer, string password)
        {
            SubjectAlternativeNameBuilder sanb = new SubjectAlternativeNameBuilder();

            sanb.AddIpAddress(IPAddress.Parse(ipaddr));
            sanb.AddDnsName(dns);

            X500DistinguishedName subject = new X500DistinguishedName($"CN={issuer}");

            using (RSA rsa = RSA.Create(2048))
            {
                var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                request.CertificateExtensions.Add(
                    new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));

                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(new OidCollection {
                    new Oid("1.3.6.1.5.5.7.3.1")
                }, false));

                request.CertificateExtensions.Add(sanb.Build());

                var certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
                certificate.FriendlyName = issuer;

                return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, password), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable));
            }
        }
示例#8
0
        public static void SanDnsMeansNoCommonNameFallback()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=zalzalak.fruit.example",
                    key,
                    HashAlgorithmName.SHA256);

                SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName("yumberry.fruit.example");
                sanBuilder.AddDnsName("*.pome.fruit.example");

                req.CertificateExtensions.Add(sanBuilder.Build());

                DateTimeOffset now       = DateTimeOffset.UtcNow;
                DateTimeOffset notBefore = now.AddMinutes(-1);
                DateTimeOffset notAfter  = now.AddMinutes(1);

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    AssertMatch(true, cert, "yumberry.fruit.example");
                    AssertMatch(true, cert, "zalzalak.pome.fruit.example");

                    // zalzalak is a pome, and our fake DNS knows that, but the certificate doesn't.
                    AssertMatch(false, cert, "zalzalak.fruit.example");
                }
            }
        }
示例#9
0
        public static void DnsNameMatchIgnoresTrailingPeriodFromParameter()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=10.0.0.1",
                    key,
                    HashAlgorithmName.SHA256);

                SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName("fruit.EXAMPLE");
                sanBuilder.AddDnsName("*.FrUIt.eXaMpLE");
                sanBuilder.AddEmailAddress("*****@*****.**");

                req.CertificateExtensions.Add(sanBuilder.Build());

                DateTimeOffset now       = DateTimeOffset.UtcNow;
                DateTimeOffset notBefore = now.AddMinutes(-1);
                DateTimeOffset notAfter  = now.AddMinutes(1);

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    AssertMatch(true, cert, "aPPlE.fruit.example.");
                    AssertMatch(true, cert, "tOmaTO.FRUIT.example.");
                    AssertMatch(false, cert, "tOmaTO.vegetable.example.");
                    AssertMatch(true, cert, "FRUit.example.");
                    AssertMatch(false, cert, "VEGetaBlE.example.");
                }
            }
        }
示例#10
0
        public static void SanDoesNotMatchIPAddressInDnsName()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=10.0.0.1",
                    key,
                    HashAlgorithmName.SHA256);

                SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName("127.0.0.1");
                sanBuilder.AddEmailAddress("*****@*****.**");

                req.CertificateExtensions.Add(sanBuilder.Build());

                DateTimeOffset now       = DateTimeOffset.UtcNow;
                DateTimeOffset notBefore = now.AddMinutes(-1);
                DateTimeOffset notAfter  = now.AddMinutes(1);

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    // 127.0.0.1 is an IP Address, but the SAN calls it a dNSName, so it won't match.
                    AssertMatch(false, cert, "127.0.0.1");

                    // Since the SAN contains no iPAddress values, we fall back to the CN.
                    AssertMatch(true, cert, "10.0.0.1");
                }
            }
        }
示例#11
0
        public static void NoPartialWildcards()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=10.0.0.1",
                    key,
                    HashAlgorithmName.SHA256);

                SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName("*berry.fruit.example");
                sanBuilder.AddDnsName("cran*.fruit.example");
                sanBuilder.AddEmailAddress("*****@*****.**");

                req.CertificateExtensions.Add(sanBuilder.Build());

                DateTimeOffset now       = DateTimeOffset.UtcNow;
                DateTimeOffset notBefore = now.AddMinutes(-1);
                DateTimeOffset notAfter  = now.AddMinutes(1);

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    AssertMatch(false, cert, "cranberry.fruit.example");
                    AssertMatch(false, cert, "cranapple.fruit.example");
                    AssertMatch(false, cert, "strawberry.fruit.example");
                }
            }
        }
示例#12
0
        public static void IPv6InCommonNameIsTextMatch()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=[fe80::1]",
                    key,
                    HashAlgorithmName.SHA256);

                SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName("huckleberry.fruit.example");
                sanBuilder.AddEmailAddress("*****@*****.**");

                req.CertificateExtensions.Add(sanBuilder.Build());

                DateTimeOffset now       = DateTimeOffset.UtcNow;
                DateTimeOffset notBefore = now.AddMinutes(-1);
                DateTimeOffset notAfter  = now.AddMinutes(1);

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    // Various text forms of fe80::1.  These would all match under IP-ID, but
                    // only the first couple match under CN-ID (case-insensitive exact)
                    AssertMatch(true, cert, "[fe80::1]");
                    AssertMatch(true, cert, "[fE80::1]");
                    AssertMatch(true, cert, "[FE80::1]");
                    AssertMatch(true, cert, "[Fe80::1]");

                    AssertMatch(false, cert, "fe80::1");
                    AssertMatch(false, cert, "[fe80:0000::1]");
                    AssertMatch(false, cert, "[fe80:0000::01]");
                }
            }
        }
示例#13
0
        /// <summary>
        /// Returns a DER-encoded PKCS#10 Certificate Signing Request for the given RSA parametes
        /// and the given hash algorithm.
        /// </summary>
        public static byte[] GenerateCsr(this RsaTool tool, IEnumerable <string> dnsNames,
                                         RSA rsa, HashAlgorithmName?hashAlgor = null)
        {
            if (hashAlgor == null)
            {
                hashAlgor = HashAlgorithmName.SHA256;
            }

            string firstName  = null;
            var    sanBuilder = new SubjectAlternativeNameBuilder();

            foreach (var n in dnsNames)
            {
                sanBuilder.AddDnsName(n);
                if (firstName == null)
                {
                    firstName = n;
                }
            }
            if (firstName == null)
            {
                throw new ArgumentException("Must specify at least one name");
            }

            var dn  = new X500DistinguishedName($"CN={firstName}");
            var csr = new CertificateRequest(dn,
                                             rsa, hashAlgor.Value, RSASignaturePadding.Pkcs1);

            csr.CertificateExtensions.Add(sanBuilder.Build());

            return(csr.CreateSigningRequest());
        }
        public static void SingleValue_Uri_UnicodeHost()
        {
            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            Assert.Throws <CryptographicException>(
                () => builder.AddUri(new Uri("http://\u65E5\u672C\u8A8E.example.org/")));
        }
示例#15
0
        /// <summary>
        /// Build the Subject Alternative name extension
        /// </summary>
        /// <param name="uris">The Uris</param>
        /// <param name="addresses">The domain names.
        /// DNS Hostnames, IPv4 or IPv6 addresses</param>
        /// <param name="critical"></param>
        public static X509Extension BuildSubjectAlternativeName(
            IEnumerable <string> uris, IEnumerable <string> addresses, bool critical)
        {
            var sanBuilder = new SubjectAlternativeNameBuilder();

            foreach (var uri in uris)
            {
                sanBuilder.AddUri(new Uri(uri));
            }
            foreach (var domainName in addresses)
            {
                if (string.IsNullOrWhiteSpace(domainName))
                {
                    continue;
                }
                if (IPAddress.TryParse(domainName, out var ipAddr))
                {
                    sanBuilder.AddIpAddress(ipAddr);
                }
                else
                {
                    sanBuilder.AddDnsName(domainName);
                }
            }
            return(sanBuilder.Build(critical));
        }
示例#16
0
        public static void SanWithNoDnsMeansDoCommonNameFallback()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=zalzalak.fruit.example",
                    key,
                    HashAlgorithmName.SHA256);

                SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddIpAddress(IPAddress.Loopback);
                sanBuilder.AddEmailAddress("*****@*****.**");

                req.CertificateExtensions.Add(sanBuilder.Build());

                DateTimeOffset now       = DateTimeOffset.UtcNow;
                DateTimeOffset notBefore = now.AddMinutes(-1);
                DateTimeOffset notAfter  = now.AddMinutes(1);

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    AssertMatch(false, cert, "yumberry.fruit.example");
                    AssertMatch(true, cert, "127.0.0.1");

                    // Since the SAN contains no dNSName values, we fall back to the CN.
                    AssertMatch(true, cert, "zalzalak.fruit.example");
                    AssertMatch(false, cert, "zalzalak.fruit.example", allowCommonName: false);
                }
            }
        }
        private static X509Certificate2 CreateSelfSigned13ServerCertificate()
        {
            using RSA rsa = RSA.Create();

            var sanBuilder = new SubjectAlternativeNameBuilder();

            sanBuilder.AddDnsName("localhost");

            var certReq = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));
            certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection {
                new Oid("1.3.6.1.5.5.7.3.1")
            }, false));
            certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
            certReq.CertificateExtensions.Add(sanBuilder.Build());

            X509Certificate2 innerCert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1));

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                using (innerCert)
                {
                    return(new X509Certificate2(innerCert.Export(X509ContentType.Pfx)));
                }
            }
            else
            {
                return(innerCert);
            }
        }
示例#18
0
        public static void WildcardRequiresSuffixToMatch()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=potato.vegetable.example",
                    key,
                    HashAlgorithmName.SHA256);

                SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName("*");
                sanBuilder.AddDnsName("*.");
                sanBuilder.AddEmailAddress("*****@*****.**");

                req.CertificateExtensions.Add(sanBuilder.Build());

                DateTimeOffset now       = DateTimeOffset.UtcNow;
                DateTimeOffset notBefore = now.AddMinutes(-1);
                DateTimeOffset notAfter  = now.AddMinutes(1);

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    AssertMatch(false, cert, "example");
                    AssertMatch(false, cert, "example.");
                }
            }
        }
示例#19
0
        public static X509Certificate2 BuildTlsSelfSignedServer(string[] domains)
        {
            var sanBuilder = new SubjectAlternativeNameBuilder();

            foreach (var domain in domains)
            {
                sanBuilder.AddDnsName(domain);
            }

            using (var rsa = RSA.Create())
            {
                var request = new CertificateRequest("CN=" + domains.First(), rsa, HashAlgorithmName.SHA256,
                                                     RSASignaturePadding.Pkcs1);

                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        new OidCollection {
                    new Oid("1.3.6.1.5.5.7.3.1")
                }, false));

                request.CertificateExtensions.Add(sanBuilder.Build());

                var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(90));

                // Hack - https://github.com/dotnet/corefx/issues/24454
                var buffer = cert.Export(X509ContentType.Pfx, (string)null);
                return(new X509Certificate2(buffer, (string)null));
            }
        }
        public void LoadCertificateAndPrivateKey()
        {
            try
            {
                Cert = new X509Certificate2(_appSettings.Certificate);
                Key  = new RSACryptoServiceProvider();

                var rsaPrivParams = UASecurity.ImportRSAPrivateKey(File.ReadAllText(_appSettings.PrivateKey));
                Key.ImportParameters(rsaPrivParams);
            }
            catch
            {
                var dn = new X500DistinguishedName($"CN={_appSettings.CommonName};OU={_appSettings.OrganizationalUnit}", X500DistinguishedNameFlags.UseSemicolons);
                SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddUri(new Uri($"urn:{_appSettings.ApplicationUri}"));

                using (RSA rsa = RSA.Create(2048))
                {
                    var request = new CertificateRequest(dn, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                    request.CertificateExtensions.Add(sanBuilder.Build());

                    var selfSignedCert = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));

                    Cert = new X509Certificate2(selfSignedCert.Export(X509ContentType.Pfx, ""), "", X509KeyStorageFlags.DefaultKeySet);

                    var certPrivateParams = rsa.ExportParameters(true);
                    File.WriteAllText(_appSettings.Certificate, UASecurity.ExportPEM(Cert));
                    File.WriteAllText(_appSettings.PrivateKey, UASecurity.ExportRSAPrivateKey(certPrivateParams));

                    Key = new RSACryptoServiceProvider();
                    Key.ImportParameters(certPrivateParams);
                }
            }
        }
示例#21
0
        internal static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string name, string?testName = null)
        {
            X509Certificate2Collection chain = new X509Certificate2Collection();

            X509ExtensionCollection extensions = new X509ExtensionCollection();

            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName(name);
            extensions.Add(builder.Build());
            extensions.Add(s_eeConstraints);
            extensions.Add(s_eeKeyUsage);
            extensions.Add(s_tlsServerEku);

            CertificateAuthority.BuildPrivatePki(
                PkiOptions.IssuerRevocationViaCrl,
                out RevocationResponder responder,
                out CertificateAuthority root,
                out CertificateAuthority intermediate,
                out X509Certificate2 endEntity,
                subjectName: name,
                testName: testName,
                keySize: 2048,
                extensions: extensions);

            chain.Add(intermediate.CloneIssuerCert());
            chain.Add(root.CloneIssuerCert());

            responder.Dispose();
            root.Dispose();
            intermediate.Dispose();

            return(endEntity, chain);
        }
        /// <inheritdoc />
        public X509Certificate2 GenerateAndSignCertificate(string subjectName)
        {
            using (RSA newKey = RSA.Create(_defaultKeyLength))
            {
                // Create the reguest
                CertificateRequest request = new CertificateRequest(subjectName, newKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                var s = new SubjectAlternativeNameBuilder();
                s.AddDnsName(subjectName.Substring("CN=".Length));

                request.CertificateExtensions.Add(s.Build());
                request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, true));

                // This is no CA
                request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));

                // Add default TLS key usages
                request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, false));


                request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection
                {
                    new Oid("1.3.6.1.5.5.7.3.1"), // Server-auth
                    new Oid("1.3.6.1.5.5.7.3.2")  // Client-auth
                }, true));

                X509Certificate2 certificate = request.Create(this._caCertificate, DateTimeOffset.UtcNow.AddDays(-1),
                                                              this._caCertificate.NotAfter.AddDays(-10), GenerateSerialNumber());

                return(certificate.CopyWithPrivateKey(newKey));
            }
        }
示例#23
0
        public static void CreateCertificate(string ip)
        {
            try
            {
                var cr = new CertificateRequest(new X500DistinguishedName("cn=ispy-local"), RSA.Create(), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                SubjectAlternativeNameBuilder subjectAlternativeNameBuilder = new SubjectAlternativeNameBuilder();
                subjectAlternativeNameBuilder.AddIpAddress(IPAddress.Parse(ip));
                var locals = MainForm.AddressListIPv4;
                foreach (var lip in locals)
                {
                    subjectAlternativeNameBuilder.AddIpAddress(lip);
                }

                cr.CertificateExtensions.Add(subjectAlternativeNameBuilder.Build());
                string    pw    = "123abc!!D";
                var       cert  = cr.CreateSelfSigned(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddYears(+1));
                var       cert2 = new X509Certificate2(cert.Export(X509ContentType.Pfx, pw), pw);
                X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);

                X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, "ispy-local", false);
                if (col.Count > 0)
                {
                    store.RemoveRange(col);
                }

                store.Add(cert2);
                store.Close();
                _sslCertificate = cert2;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "X509 Create");
            }
        }
        public X509Certificate2 GenerateCertificate(DateTime? notBefore = null, DateTime? notAfter = null)
        {
            var name = Guid.NewGuid().ToString("N");
            var builder = new SubjectAlternativeNameBuilder();
            builder.AddDnsName(name);

            var dn = new X500DistinguishedName($"CN={name}");
            using (var rsa = RSA.Create(2048))
            {
                var request = new CertificateRequest(dn, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                var usage = new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyAgreement, true);
                request.CertificateExtensions.Add(usage);

                var oids = new OidCollection
                {
                    new Oid("1.3.6.1.5.5.7.3.1"), // Server authentication
                    new Oid("1.3.6.1.5.5.7.3.2") // Client authentication
                };

                request.CertificateExtensions.Add(
                   new X509EnhancedKeyUsageExtension(oids, false));

                request.CertificateExtensions.Add(builder.Build());

                var certificate = request.CreateSelfSigned(new DateTimeOffset(notBefore ?? DateTime.UtcNow.AddMinutes(-5)), new DateTimeOffset(notAfter ?? DateTime.UtcNow.AddMinutes(5)));
                var bytes = certificate.Export(X509ContentType.Pfx);
                return new X509Certificate2(bytes, null as string, X509KeyStorageFlags.Exportable); // don't ask me why, but this is required for some tests to work; i.e. Mtls tests
            }
        }
示例#25
0
        public X509Certificate2 CompleteRootCaRequest(string certName, CertificateRequest request,
                                                      SubjectAlternativeNameBuilder sanBuilder, int validDays, string keyPassword, bool useCrl,
                                                      bool exportPfx, string exportPath, bool addRootCaToComputerRootStore, bool addRootCaToComputerPersonalStore)
        {
            var sanExtension = sanBuilder.Build();

            // set this cert as a CA
            request.CertificateExtensions.Add(
                new X509BasicConstraintsExtension(true, false, 0, true));

            request.CertificateExtensions.Add(sanExtension);
            //request.CertificateExtensions
            var newRoot = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(validDays)));

            // System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
            newRoot.FriendlyName = certName;

            if (exportPfx)
            {
                ExportCaPfx(newRoot, exportPath, keyPassword);
            }
            if (addRootCaToComputerRootStore)
            {
                AddRootCaToStore(newRoot, StoreLocation.LocalMachine, StoreName.Root);
            }
            if (addRootCaToComputerPersonalStore)
            {
                AddRootCaToStore(newRoot, StoreLocation.LocalMachine, StoreName.My);
            }


            return(new X509Certificate2(newRoot.Export(X509ContentType.Pfx, keyPassword), keyPassword, X509KeyStorageFlags.MachineKeySet));
        }
示例#26
0
        private X509Certificate2 GenerateCertificate()
        {
            string CertificateName = "sportal.qlikcloud.com";
            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();

            sanBuilder.AddDnsName("localhost");
            sanBuilder.AddDnsName("qlikcloud.com");

            X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN={CertificateName}");

            using (RSA rsa = RSA.Create(2048))
            {
                var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                request.CertificateExtensions.Add(
                    new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));


                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        new OidCollection {
                    new Oid("1.3.6.1.5.5.7.3.1")
                }, false));

                request.CertificateExtensions.Add(sanBuilder.Build());

                X509Certificate2 certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(825)));

                return(certificate);
            }
        }
示例#27
0
        static X509Certificate2 BuildSelfSignedServerCertificate(string certificateName)
        {
            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();

            sanBuilder.AddIpAddress(IPAddress.Loopback);
            //sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
            sanBuilder.AddDnsName(certificateName);
            //sanBuilder.AddDnsName("localhost");
            //sanBuilder.AddDnsName(Environment.MachineName);

            X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN={certificateName}");

            using (RSA rsa = RSA.Create(2048))
            {
                var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                request.CertificateExtensions.Add(
                    new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));

                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        new OidCollection {
                    new Oid("1.3.6.1.5.5.7.3.1")
                }, false));

                request.CertificateExtensions.Add(sanBuilder.Build());

                var certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
                certificate.FriendlyName = certificateName;

                return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, "SomePassword"), "SomePassword", X509KeyStorageFlags.MachineKeySet));
            }
        }
示例#28
0
        /// <summary>
        /// Generate a new 2048 bit RSA key and cert bundle and self sign the public key with the private key
        /// https://stackoverflow.com/a/50138133/6620171
        /// </summary>
        /// <param name="CommonName"></param>
        /// <returns></returns>
        private static X509Certificate2 BuildSelfSignedServerCertificate(string CommonName, int daysUntilExpire)
        {
            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();

            sanBuilder.AddIpAddress(IPAddress.Loopback);
            sanBuilder.AddDnsName("localhost");
            sanBuilder.AddDnsName(Environment.MachineName);
            X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN={CommonName}");

            using (RSA rsa = RSA.Create(2048))
            {
                CertificateRequest request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
                request.CertificateExtensions.Add(
                    new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));
                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        new OidCollection {
                    new Oid("1.3.6.1.5.5.7.3.1")
                }, false));
                request.CertificateExtensions.Add(sanBuilder.Build());
                X509Certificate2 certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(daysUntilExpire)));
                //certificate.FriendlyName = CommonName; // Linux: System.PlatformNotSupportedException: The FriendlyName value cannot be set on Unix.
                return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, "WeNeedASaf3rPassword"), "WeNeedASaf3rPassword", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable));
            }
        }
示例#29
0
        public static void EnumerateDnsNames(LoadMode loadMode)
        {
            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName("foo");
            builder.AddIpAddress(IPAddress.Loopback);
            builder.AddUserPrincipalName("*****@*****.**");
            builder.AddIpAddress(IPAddress.IPv6Loopback);
            builder.AddDnsName("*.foo");
            X509Extension built = builder.Build(true);

            X509SubjectAlternativeNameExtension ext;

            switch (loadMode)
            {
            case LoadMode.CopyFrom:
                ext = new X509SubjectAlternativeNameExtension();
                ext.CopyFrom(built);
                break;

            case LoadMode.Array:
                ext = new X509SubjectAlternativeNameExtension(built.RawData);
                break;

            case LoadMode.Span:
                byte[] tmp = new byte[built.RawData.Length + 2];
                built.RawData.AsSpan().CopyTo(tmp.AsSpan(1));
                ext = new X509SubjectAlternativeNameExtension(tmp.AsSpan()[1..^ 1]);
        public X509Certificate2 GenerateSelfSignedCertificate(string subjectName, bool doNotAddDnsName, int validDays)
        {
            using (RSA key = RSA.Create(_defaultKeyLength))
            {
                CertificateRequest request = new CertificateRequest(subjectName, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, true));

                // This is CA
                request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));

                // Add default TLS key usages
                request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));


                request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection
                {
                    new Oid("1.3.6.1.5.5.7.3.1"), // Server-auth
                    new Oid("1.3.6.1.5.5.7.3.2")  // Client-auth
                }, true));

                if (false == doNotAddDnsName)
                {
                    var s = new SubjectAlternativeNameBuilder();
                    s.AddDnsName(subjectName.Substring("CN=".Length));
                    request.CertificateExtensions.Add(s.Build());
                }

                X509Certificate2 certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1),
                                                                        DateTimeOffset.UtcNow.AddDays(validDays));


                return(certificate);
            }
        }