示例#1
0
        public static void TestInvalidAia()
        {
            using (RSA key = RSA.Create())
            {
                CertificateRequest rootReq = new CertificateRequest(
                    "CN=Root",
                    key,
                    HashAlgorithmName.SHA256,
                    RSASignaturePadding.Pkcs1);

                rootReq.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(true, false, 0, true));

                CertificateRequest certReq = new CertificateRequest(
                    "CN=test",
                    key,
                    HashAlgorithmName.SHA256,
                    RSASignaturePadding.Pkcs1);

                certReq.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(false, false, 0, false));

                certReq.CertificateExtensions.Add(
                    new X509Extension(
                        "1.3.6.1.5.5.7.1.1",
                        new byte[] { 5 },
                        critical: false));

                DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddDays(-1);
                DateTimeOffset notAfter  = notBefore.AddDays(30);

                using (X509Certificate2 root = rootReq.CreateSelfSigned(notBefore, notAfter))
                    using (X509Certificate2 ee = certReq.Create(root, notBefore, notAfter, root.GetSerialNumber()))
                    {
                        X509Chain chain = new X509Chain();
                        chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                        Assert.False(chain.Build(ee));
                        Assert.Equal(1, chain.ChainElements.Count);
                        Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags());
                    }
            }
        }
示例#2
0
        public FidoU2f()
        {
            _aaguid = Guid.Empty;
            _attestationObject.Add("fmt", "fido-u2f");
            X509Certificate2 attestnCert;

            using (var ecdsaAtt = ECDsa.Create(ECCurve.NamedCurves.nistP256))
            {
                var attRequest = new CertificateRequest("CN=U2FTesting, OU=Authenticator Attestation, O=FIDO2-NET-LIB, C=US", ecdsaAtt, HashAlgorithmName.SHA256);

                attRequest.CertificateExtensions.Add(notCAExt);

                using (attestnCert = attRequest.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(2)))
                {
                    var X5c = CBORObject.NewArray()
                              .Add(CBORObject.FromObject(attestnCert.RawData));
                    var ecparams = ecdsaAtt.ExportParameters(true);

                    _credentialPublicKey = Fido2Tests.MakeCredentialPublicKey(COSE.KeyType.EC2, COSE.Algorithm.ES256, COSE.EllipticCurve.P256, ecparams.Q.X, ecparams.Q.Y);

                    var x            = _credentialPublicKey.GetCBORObject()[CBORObject.FromObject(COSE.KeyTypeParameter.X)].GetByteString();
                    var y            = _credentialPublicKey.GetCBORObject()[CBORObject.FromObject(COSE.KeyTypeParameter.Y)].GetByteString();
                    var publicKeyU2F = new byte[1] {
                        0x4
                    }.Concat(x).Concat(y).ToArray();

                    var verificationData = new byte[1] {
                        0x00
                    };
                    verificationData = verificationData
                                       .Concat(_rpIdHash)
                                       .Concat(_clientDataHash)
                                       .Concat(_credentialID)
                                       .Concat(publicKeyU2F.ToArray())
                                       .ToArray();

                    byte[] signature = Fido2Tests.SignData(COSE.KeyType.EC2, COSE.Algorithm.ES256, verificationData, ecdsaAtt, null, null);

                    _attestationObject.Add("attStmt", CBORObject.NewMap().Add("x5c", X5c).Add("sig", signature));
                }
            }
        }
示例#3
0
        private static X509Certificate2 GenerateSelfSignedCertificate(string name)
        {
            var distinguishedName = new X500DistinguishedName($"CN={name}");

            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("1.3.6.1.5.5.7.3.1"),         // server auth
                    new Oid("1.3.6.1.5.5.7.3.2")          // client auth
                }, false));

                // When creating the localhost certificate, add the other names
                if (string.Equals(name, "localhost", StringComparison.OrdinalIgnoreCase))
                {
                    var sanBuilder = new SubjectAlternativeNameBuilder();
                    sanBuilder.AddIpAddress(IPAddress.Loopback);
                    sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
                    sanBuilder.AddDnsName("localhost");
                    sanBuilder.AddDnsName(Environment.MachineName);

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

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

                var tempPwd = Guid.NewGuid().ToString();

                return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, tempPwd), tempPwd, X509KeyStorageFlags.MachineKeySet));
            }
        }
        /// <summary>
        ///     Create a Self Signed Certificate
        /// </summary>
        /// <param name="certName"></param>
        /// <returns></returns>
        private static X509Certificate2 CreateSelfSignedCert(string certName)
        {
            ECDsa ecdsaKey = ECDsa.Create();
            CertificateRequest certificateRequest = new CertificateRequest(certName, ecdsaKey, HashAlgorithmName.SHA256);
            // We have to export cert to dummy cert since `CreateSelfSigned` creates a cert without a private key.
            X509Certificate2 cert = certificateRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));

            X509Certificate2 dummyCert = null;

            if (PowerShell.Authentication.Helpers.OperatingSystem.IsMacOS())
            {
                dummyCert = new X509Certificate2(cert.Export(X509ContentType.Pfx, "P@55w0rd"), "P@55w0rd", X509KeyStorageFlags.Exportable);
            }
            else
            {
                dummyCert = new X509Certificate2(cert.Export(X509ContentType.Pfx, "P@55w0rd"), "P@55w0rd", X509KeyStorageFlags.PersistKeySet);
            }

            return(dummyCert);
        }
示例#5
0
        public void SetUp()
        {
            SetUpProvider();
            _context = new DefaultHttpContext();
            X509Certificate2 certificate;

            using (RSA rsa = RSA.Create())
            {
                var certReq    = new CertificateRequest("CN=eventstoredb-node", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                var sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddEmailAddress("*****@*****.**");
                sanBuilder.AddUserPrincipalName("*****@*****.**");
                sanBuilder.AddUri(new Uri("http://localhost"));
                certReq.CertificateExtensions.Add(sanBuilder.Build());
                certificate = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1));
            }

            _context.Connection.ClientCertificate = certificate;
            _authenticateResult = _provider.Authenticate(_context, out _authenticateRequest);
        }
        public X509Certificate2 CreateSelfSignedCert(string subject)
        {
            CertificateRequest request = new CertificateRequest($"CN={subject},OU=Access Manager,O=Lithnet", RSA.Create(4096), HashAlgorithmName.SHA384, RSASignaturePadding.Pss);

            var enhancedKeyUsage = new OidCollection
            {
                new Oid(LithnetAccessManagerEku, "Lithnet Access Manager Encryption")
            };

            request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(enhancedKeyUsage, critical: true));
            request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyEncipherment, true));
            request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));

            X509Certificate2 cert = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTime.UtcNow.AddYears(20));
            string           p    = Guid.NewGuid().ToString();
            var raw = cert.Export(X509ContentType.Pfx, p);
            var f   = new X509Certificate2(raw, p, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

            return(f);
        }
示例#7
0
        static X509Certificate2 CreateClientCertificate(string name)
        {
            X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN={name}");

            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("1.3.6.1.5.5.7.3.2")
                }, false));

                return(request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650))));
            }
        }
示例#8
0
        public static async Task <X509Certificate2> LoadOrGenerateCertificate(string path)
        {
            if (!File.Exists(path))
            {
                var distinguishedName = new X500DistinguishedName("CN=helium");
                using var rsa = RSA.Create(2048);

                var certRequest = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                certRequest.CertificateExtensions.Add(new X509KeyUsageExtension(
                                                          X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false
                                                          ));

                var cert = certRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1000));
                await File.WriteAllBytesAsync(path, cert.Export(X509ContentType.Pfx));

                return(cert);
            }

            return(new X509Certificate2(await File.ReadAllBytesAsync(path)));
        }
示例#9
0
        public static void NoMatchAndEmptyCommonName()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=,ST=Idaho",
                    key,
                    HashAlgorithmName.SHA256);

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

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    AssertMatch(false, cert, "FRUit.example");
                    AssertMatch(false, cert, "potato.vegetable.example");
                }
            }
        }
示例#10
0
        public static void UniqueExtensions()
        {
            using (RSA rsa = RSA.Create())
            {
                CertificateRequest request = new CertificateRequest(
                    "CN=Double Extension Test",
                    rsa,
                    HashAlgorithmName.SHA256);

                request.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(true, false, 0, true));

                request.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(true, false, 0, true));

                DateTimeOffset now = DateTimeOffset.UtcNow;

                Assert.Throws <InvalidOperationException>(() => request.CreateSelfSigned(now, now.AddDays(1)));
            }
        }
示例#11
0
        public static X509Certificate2 CreateSelfSignedCertificate(string address, string DistinguishedName = "")
        {
            if (DistinguishedName == "")
            {
                DistinguishedName = "CN=" + address;
            }
            using (RSA rsa = RSA.Create(2048))
            {
                var request = new CertificateRequest(new X500DistinguishedName(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));
                SubjectAlternativeNameBuilder subjectAlternativeName = new SubjectAlternativeNameBuilder();
                subjectAlternativeName.AddIpAddress(IPAddress.Parse(address));

                request.CertificateExtensions.Add(subjectAlternativeName.Build());
                return(request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650))));
            }
        }
示例#12
0
            private void LoadCertificateAndPrivateKey()
            {
                try
                {
                    // Try to load existing (public key) and associated private key
                    appCertificate  = new X509Certificate2("ServerCert.der");
                    cryptPrivateKey = new RSACryptoServiceProvider();

                    var rsaPrivParams = UASecurity.ImportRSAPrivateKey(File.ReadAllText("ServerKey.pem"));
                    cryptPrivateKey.ImportParameters(rsaPrivParams);
                }
                catch
                {
                    // Make a new certificate (public key) and associated private key
                    var dn = new X500DistinguishedName("CN=Client certificate;OU=Demo organization",
                                                       X500DistinguishedNameFlags.UseSemicolons);
                    SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                    sanBuilder.AddUri(new Uri("urn:DemoApplication"));

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

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

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

                        appCertificate = new X509Certificate2(certificate.Export(X509ContentType.Pfx, ""),
                                                              "", X509KeyStorageFlags.DefaultKeySet);

                        var certPrivateParams = rsa.ExportParameters(true);
                        File.WriteAllText("ServerCert.der", UASecurity.ExportPEM(appCertificate));
                        File.WriteAllText("ServerKey.pem", UASecurity.ExportRSAPrivateKey(certPrivateParams));

                        cryptPrivateKey = new RSACryptoServiceProvider();
                        cryptPrivateKey.ImportParameters(certPrivateParams);
                    }
                }
            }
示例#13
0
        private X509Certificate2 buildSelfSignedServerCertificate(string name)
        {
            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();

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

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

            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)));

            // try
            // {
            //     certificate.FriendlyName = name;
            // }
            // catch (Exception) { }

            return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, "WeNeedASaf3rPassword"),
                                        "WeNeedASaf3rPassword", X509KeyStorageFlags.UserKeySet));
        }
示例#14
0
        public static void OnlyValidHostnamesAccepted(bool addSanExt)
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=John Smith",
                    key,
                    HashAlgorithmName.SHA256);

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

                if (addSanExt)
                {
                    SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
                    sanBuilder.AddDnsName("fruit.example");
                    sanBuilder.AddDnsName("*.fruit.example");
                    sanBuilder.AddDnsName("*.*.fruit.example");
                    sanBuilder.AddDnsName("apple.*.fruit.example");
                    sanBuilder.AddDnsName("rambutan.fruit.example");
                    sanBuilder.AddEmailAddress("*****@*****.**");

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

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname("John Smith"));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname("*.pomme.fruit.example"));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname(".pomme.fruit.example"));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname("*berry.fruit.example"));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname("cran*.fruit.example"));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname("cran*.fruit.example"));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname(""));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname("."));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname("*."));
                    Assert.Throws <ArgumentException>("hostname", () => cert.MatchesHostname("*"));
                }
            }
        }
示例#15
0
        public static void TestGost2012_256UnicodeCn()
        {
            var cn = $"CN={"Unicode_ёёёё"}";

            using (var provider = GostCertificateRequestTests.GenerateProvider(KeyNumber.Exchange, Constants.Algorithms.Gost3410_2012_256))
            {
                try
                {
                    CertificateRequest certificateRequest = new CertificateRequest(
                        cn,
                        (Gost3410_2012_256)provider,
                        HashAlgorithmName.Gost3411_2012_256);

                    certificateRequest.CertificateExtensions.Add(
                        new X509KeyUsageExtension(
                            X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.KeyEncipherment,
                            false));

                    var oidCollection = new OidCollection();
                    // Проверка подлинности клиента (1.3.6.1.5.5.7.3.2)
                    oidCollection.Add(new Oid("1.3.6.1.5.5.7.3.2"));

                    certificateRequest.CertificateExtensions.Add(
                        new X509EnhancedKeyUsageExtension(
                            oidCollection,
                            true));

                    certificateRequest.CertificateExtensions.Add(
                        new X509SubjectKeyIdentifierExtension(certificateRequest.PublicKey, false));

                    var cert = certificateRequest.CreateSelfSigned(
                        DateTimeOffset.Now.AddDays(-45),
                        (DateTimeOffset.Now.AddDays(45)));

                    Assert.Equal(cn, cert.Subject);
                }
                finally
                {
                }
            }
        }
示例#16
0
        public void TestU2fAttCertNotP256()
        {
            using (var ecdsaAtt = ECDsa.Create(ECCurve.NamedCurves.nistP384))
            {
                var attRequest = new CertificateRequest("CN=U2FTesting, OU=Authenticator Attestation, O=FIDO2-NET-LIB, C=US", ecdsaAtt, HashAlgorithmName.SHA256);

                attRequest.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(false, false, 0, false));

                using (var attestnCert = attRequest.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(2)))
                {
                    _attestationObject["attStmt"].Set("x5c", CBORObject.NewArray()
                                                      .Add(CBORObject.FromObject(attestnCert.RawData)));
                    ;
                }
            }

            var ex = Assert.ThrowsAsync <Fido2VerificationException>(() => MakeAttestationResponse());

            Assert.Equal("Attestation certificate public key is not an Elliptic Curve (EC) public key over the P-256 curve", ex.Result.Message);
        }
        /// <summary>
        /// Create self-signed certificate with subject name. .
        /// </summary>
        /// <param name="subjectName">Certificate subject name, example: "CN=my-certificate, O=some-organisation".</param>
        /// <param name="expiry">Certificate expiry, default 365 days.</param>
        public static Task <X509Certificate2> CreateSelfSignedCertificateAsync(this string subjectName, TimeSpan?expiry = null)
        {
            using (var rsa = RSA.Create(2048))
            {
                var certRequest = new CertificateRequest(subjectName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                certRequest.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(false, false, 0, false));

                certRequest.CertificateExtensions.Add(
                    new X509SubjectKeyIdentifierExtension(certRequest.PublicKey, false));

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

                var now = DateTimeOffset.UtcNow;
                return(Task.FromResult(certRequest.CreateSelfSigned(now.AddDays(-1), now.Add(expiry ?? TimeSpan.FromDays(365)))));
            }
        }
示例#18
0
        public static void CommonNameMatchDoesNotIgnoreTrailingPeriodFromValue()
        {
            using (ECDsa key = ECDsa.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    "CN=fruit.example.",
                    key,
                    HashAlgorithmName.SHA256);

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

                using (X509Certificate2 cert = req.CreateSelfSigned(notBefore, notAfter))
                {
                    AssertMatch(true, cert, "FRUit.example.");
                    AssertMatch(false, cert, "FRUit.example.", allowCommonName: false);
                    AssertMatch(false, cert, "FRUit.example");
                }
            }
        }
示例#19
0
            private KeyCertificatePair GenerateKeyCertificatePair()
            {
                using (RSA rsa = RSA.Create())
                {
                    var certReq               = new CertificateRequest("CN=hello", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                    var certificate           = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1));
                    var pemCertificateBuilder = new StringBuilder();
                    pemCertificateBuilder.AppendLine("-----BEGIN CERTIFICATE-----");
                    pemCertificateBuilder.AppendLine(Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
                    pemCertificateBuilder.AppendLine("-----END CERTIFICATE-----");
                    var pemCertificate = pemCertificateBuilder.ToString();

                    var pemKeyBuilder = new StringBuilder();
                    pemKeyBuilder.AppendLine("-----BEGIN RSA PRIVATE KEY-----");
                    pemKeyBuilder.AppendLine(Convert.ToBase64String(rsa.ExportRSAPrivateKey(), Base64FormattingOptions.InsertLineBreaks));
                    pemKeyBuilder.AppendLine("-----END RSA PRIVATE KEY-----");
                    var pemKey = pemKeyBuilder.ToString();

                    return(new KeyCertificatePair(pemCertificate, pemKey));
                }
            }
示例#20
0
        // Generate a self-signed certificate.
        private static X509Certificate2 buildSelfSignedServerCertificate(string password)
        {
            const string CertificateName      = @"Microsoft Azure Federated SSO Certificate TEST";
            DateTime     certificateStartDate = DateTime.UtcNow;
            DateTime     certificateEndDate   = certificateStartDate.AddYears(2).ToUniversalTime();

            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));

                var certificate = request.CreateSelfSigned(new DateTimeOffset(certificateStartDate), new DateTimeOffset(certificateEndDate));
                certificate.FriendlyName = CertificateName;

                return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, password), password, X509KeyStorageFlags.Exportable));
            }
        }
示例#21
0
        public static void GetExample()
        {
            var ecdsa = ECDsa.Create();
            var certificateRequest = new CertificateRequest("cn=luisdeol", ecdsa, HashAlgorithmName.SHA256);
            var certificate        = certificateRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(1));

            var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            // Saving CER file, containing public key.
            var base64StringCerContent = Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks);
            var cerContent             = "-----BEGIN CERTIFICATE-----\r\n"
                                         + base64StringCerContent
                                         + "\r\n-----END CERTIFICATE-----";

            File.WriteAllText($"{baseDirectory}certificate.cer", cerContent);

            // Saving PFX file, containing private key.
            var pfxBytes = certificate.Export(X509ContentType.Pfx, "1ns3rt@g00dp@ssw0rd");

            File.WriteAllBytes($"{baseDirectory}certificate.pfx", pfxBytes);
        }
示例#22
0
        public static void VerifyNumericStringSubject()
        {
            X500DistinguishedName dn = new X500DistinguishedName(
                "30283117301506052901020203120C313233203635342037383930310D300B0603550403130454657374".HexToByteArray());

            using (RSA key = RSA.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    dn,
                    key,
                    HashAlgorithmName.SHA256,
                    RSASignaturePadding.Pkcs1);

                DateTimeOffset now = DateTimeOffset.UtcNow;

                using (X509Certificate2 cert = req.CreateSelfSigned(now.AddDays(-1), now.AddDays(1)))
                {
                    Assert.Equal("CN=Test, OID.1.1.1.2.2.3=123 654 7890", cert.Subject);
                }
            }
        }
示例#23
0
        public X509Certificate2 CreateSelfSignedCertificate(string certificateName, string dnsName)
        {
            var sanBuilder = new SubjectAlternativeNameBuilder();

            sanBuilder.AddIpAddress(IPAddress.Loopback);
            sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
            sanBuilder.AddDnsName(dnsName);
            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("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.AddYears(10)));

            certificate.FriendlyName = certificateName;

            return(certificate);
        }
示例#24
0
        private static IEnumerable <object[]> GetThumbprintsGenerated()
        {
            var sanBuilder = new SubjectAlternativeNameBuilder();

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

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

            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("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)));

                newCert = new X509Certificate2(certificate.Export(X509ContentType.Pfx, "WeNeedASaf3rPassword"), "WeNeedASaf3rPassword", X509KeyStorageFlags.MachineKeySet);
            }

            using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser, OpenFlags.ReadWrite))
            {
                store.Add(newCert);
            }

            yield return(new object[] { newCert.Thumbprint });
        }
示例#25
0
        // Ref.: https://stackoverflow.com/a/50138133/1826

        public static X509Certificate2 GenerateSelfSignedCertificate(string commonName) // subject is the entity validated or verified by the certificate
        {
            var distinguishedName = new X500DistinguishedName($"CN={commonName}");

            // Could contain:
            // CN= common name, the end­entity being covered, example, a website or www.example.com
            // C= country
            // ST= state or province within country
            // L= location, nominally an address but ambiguously used except in EV certificates where it is rigorously defined
            // OU= organizational unit name, a company division name or similar sub­structure
            // O= organization name

            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("1.3.6.1.5.5.7.3.1")
                }, false));

                // I think only required if using for SSL?
                //request.CertificateExtensions.Add(LocalSubjectAlternativeName());

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

                certificate.FriendlyName = commonName;

                return(certificate);

                // Why do this?
                //return new X509Certificate2(certificate.Export(X509ContentType.Pfx, Constants.Password), Constants.Password, X509KeyStorageFlags.MachineKeySet);
            }
        }
        public static void ECDSA_Signing_RSAPublicKey()
        {
            using (RSA rsa = RSA.Create())
                using (ECDsa ecdsa = ECDsa.Create())
                {
                    var request = new CertificateRequest(
                        new X500DistinguishedName("CN=Test"),
                        ecdsa,
                        HashAlgorithmName.SHA256);

                    request.CertificateExtensions.Add(
                        new X509BasicConstraintsExtension(true, false, 0, true));

                    DateTimeOffset now = DateTimeOffset.UtcNow;

                    using (X509Certificate2 cert = request.CreateSelfSigned(now, now.AddDays(1)))
                    {
                        X509SignatureGenerator rsaGenerator =
                            X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1);

                        request = new CertificateRequest(
                            new X500DistinguishedName("CN=Leaf"),
                            rsaGenerator.PublicKey,
                            HashAlgorithmName.SHA256);

                        byte[] serialNumber = { 1, 1, 2, 3, 5, 8, 13 };

                        Assert.Throws <ArgumentException>(
                            () => request.Create(cert, now, now.AddHours(3), serialNumber));

                        X509SignatureGenerator ecdsaGenerator =
                            X509SignatureGenerator.CreateForECDsa(ecdsa);

                        // Passes with the generator
                        using (request.Create(cert.SubjectName, ecdsaGenerator, now, now.AddHours(3), serialNumber))
                        {
                        }
                    }
                }
        }
        //deprecating
        public X509Certificate2 CreateRootCaRSA(string certificateName, SubjectAlternativeNameBuilder sanBuilder,
                                                HashAlgorithmName hash, int keySize, int validDays, string keyPassword,
                                                bool useCRL, bool addRootCaToComputerRootStore, bool addRootCaToComputerPersonalStore)
        {
            X500DistinguishedName dn = new X500DistinguishedName($"CN={certificateName}");

            RSA key = RSA.Create(keySize);

            var request = new CertificateRequest(dn, key, hash, RSASignaturePadding.Pkcs1);

            var sanExtension = sanBuilder.Build();

            request.CertificateExtensions.Add(sanExtension);

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

            certificate.FriendlyName = certificateName;

            key.Dispose();

            return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, keyPassword), keyPassword, X509KeyStorageFlags.MachineKeySet));
        }
        private static void SimpleSelfSign(CertificateRequest request, string expectedKeyOid, bool exportPfx)
        {
            request.CertificateExtensions.Add(
                new X509EnhancedKeyUsageExtension(new OidCollection {
                new Oid("1.3.6.1.5.5.7.3.1")
            }, false));

            DateTimeOffset now = DateTimeOffset.UtcNow;

            using (X509Certificate2 newCert = request.CreateSelfSigned(now, now.AddDays(90)))
            {
                Assert.True(newCert.HasPrivateKey);

                Assert.Equal("CN=localhost", newCert.Subject);
                Assert.Equal(expectedKeyOid, newCert.GetKeyAlgorithm());
                Assert.Equal(1, newCert.Extensions.Count);

                X509Extension extension = newCert.Extensions["2.5.29.37"];
                Assert.NotNull(extension);

                X509EnhancedKeyUsageExtension ekuExtension = (X509EnhancedKeyUsageExtension)extension;
                Assert.Equal(1, ekuExtension.EnhancedKeyUsages.Count);
                Assert.Equal("1.3.6.1.5.5.7.3.1", ekuExtension.EnhancedKeyUsages[0].Value);

                // Ideally the serial number is 8 bytes.  But maybe it accidentally started with 0x00 (1/256),
                // or 0x0000 (1/32768), or even 0x00000000 (1/4 billion). But that's where we draw the line.
                string serialNumber = newCert.SerialNumber;
                // Using this construct so the value gets printed in a failure, instead of just the length.
                Assert.True(
                    serialNumber.Length >= 8 && serialNumber.Length <= 18,
                    $"Serial number ({serialNumber}) should be between 4 and 9 bytes, inclusive");

                if (exportPfx)
                {
                    byte[] pfx = newCert.Export(X509ContentType.Pkcs12, nameof(SimpleSelfSign));
                    Assert.InRange(pfx.Length, 100, int.MaxValue);
                }
            }
        }
示例#29
0
        public static X509Certificate2 CreateServerSelfSignedCertificate(string name = "localhost")
        {
            using (RSA root = RSA.Create())
            {
                CertificateRequest req = new CertificateRequest(
                    $"CN={name}",
                    root,
                    HashAlgorithmName.SHA256,
                    RSASignaturePadding.Pkcs1);

                req.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
                req.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(req.PublicKey, false));
                req.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment, false));
                req.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        new OidCollection()
                {
                    new Oid("1.3.6.1.5.5.7.3.1", null),
                }, false));


                SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();
                builder.AddDnsName(name);
                builder.AddIpAddress(IPAddress.Loopback);
                builder.AddIpAddress(IPAddress.IPv6Loopback);
                req.CertificateExtensions.Add(builder.Build());

                DateTimeOffset start = DateTimeOffset.UtcNow.AddMinutes(-5);
                DateTimeOffset end   = start.AddMonths(1);

                X509Certificate2 cert = req.CreateSelfSigned(start, end);
                if (PlatformDetection.IsWindows)
                {
                    cert = new X509Certificate2(cert.Export(X509ContentType.Pfx));
                }

                return(cert);
            }
        }
示例#30
0
        private static X509Certificate2 buildSelfSignedServerCertificate(string CertificateName, string password)
        {
            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();

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

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

            using (RSA rsa = RSA.Create(2048 * 2))
            {
                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)));
                bool isWindows   = System.Runtime.InteropServices.RuntimeInformation
                                   .IsOSPlatform(OSPlatform.Windows);
                if (isWindows)
                {
                    certificate.FriendlyName = CertificateName;
                }

                return(certificate);
                // return new X509Certificate2(certificate.Export(X509ContentType.Pfx, password), password, X509KeyStorageFlags.MachineKeySet);
            }
        }