Exemple #1
0
        public void DistinguishedName_SpaceDot()
        {
            string dnStr = @"CN=John,OU=Employees,O=adatum Inc.,C=US";
            var    dn    = new DistinguishedName(dnStr);

            Assert.AreEqual(dn.ToString(), dnStr);
            Assert.AreEqual(4, dn.Components.Count);
        }
Exemple #2
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameContainsMultvaluedRelativeDN()
        {
            // Arrange
            var dn = new DistinguishedName("CN=Dzingai + SN=Smith,CN=Users,DC=example,DC=com");

            // Act

            // Assert
            Assert.Equal("CN=Dzingai+SN=Smith,CN=Users,DC=example,DC=com", dn.ToString());
        }
Exemple #3
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameContainsHexEncodedBinaryValue()
        {
            // Arrange
            var dn = new DistinguishedName("CN=#4A756C69616E");

            // Act

            // Assert
            Assert.Equal("CN=Julian", dn.ToString());
        }
Exemple #4
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameContainsEscapedSpace()
        {
            // Arrange
            var dn = new DistinguishedName("CN=\"Julian\\ Easterling\"");

            // Act

            // Assert
            Assert.Equal("CN=Julian Easterling", dn.ToString());
        }
Exemple #5
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameContainsEscapedSpecialCharacters()
        {
            // Arrange
            var dn = new DistinguishedName(@"OU=""\,\=\+\<\>\#\;\\\ \\""");

            // Act

            // Assert
            Assert.Equal(@"OU=\,\=\+\<\>\#\;\\ \\", dn.ToString());
        }
Exemple #6
0
        public void Constructor_Should_ParseCorrectly_When_ProvidedWithDCComponents()
        {
            // Arrange
            var dn = new DistinguishedName("CN=TestUser,OU=People,DC=hdq,DC=corp,DC=example,DC=com");

            // Act

            // Assert
            Assert.Equal("CN=TestUser,OU=People,DC=hdq,DC=corp,DC=example,DC=com", dn.ToString());
        }
Exemple #7
0
        public void Constructor_Should_ParseCorrectly_When_ProvidedWithoutDCComponents()
        {
            // Arrange
            var dn = new DistinguishedName("CN=TestUser,OU=People,O=Example Inc.,C=US");

            // Act

            // Assert
            Assert.Equal("CN=TestUser,OU=People,O=Example Inc.,C=US", dn.ToString());
        }
Exemple #8
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameHasSemicolons()
        {
            // Arrange
            var dn = new DistinguishedName("CN=TestUser;OU=People,DC=hdq,DC=corp;DC=example;DC=com");

            // Act

            // Assert
            Assert.Equal("CN=TestUser,OU=People,DC=hdq,DC=corp,DC=example,DC=com", dn.ToString());
        }
Exemple #9
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameIsAnEmptyString()
        {
            // Arrange
            var dn = new DistinguishedName(string.Empty);

            // Act

            // Assert
            Assert.Equal(string.Empty, dn.ToString());
        }
Exemple #10
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameHasBlankValue()
        {
            // Arrange
            var dn = new DistinguishedName("CN=,OU=People,DC=corp,DC=example,DC=com");

            // Act

            // Assert
            Assert.Equal("CN=,OU=People,DC=corp,DC=example,DC=com", dn.ToString());
        }
Exemple #11
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameDoesNotReallyContainsAnOID()
        {
            // Arrange
            var dn = new DistinguishedName("OID33A2=Jay");

            // Act

            // Assert
            Assert.Equal("OID33A2=Jay", dn.ToString());
        }
Exemple #12
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameContainsQuotedString()
        {
            // Arrange
            var dn = new DistinguishedName("CN=Julian,OU=\"Users And Computers\",OU=HDQRK");

            // Act

            // Assert
            Assert.Equal("CN=Julian,OU=Users And Computers,OU=HDQRK", dn.ToString());
        }
Exemple #13
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameContainsOIDWithZeroPart()
        {
            // Arrange
            var dn = new DistinguishedName("34.0.21=Jay");

            // Act

            // Assert
            Assert.Equal("34.0.21=Jay", dn.ToString());
        }
Exemple #14
0
        public void Constructor_Should_ParseCorrectly_When_DistinguishedNameContainsHexEncodedBinaryValueAtEnd()
        {
            // Arrange
            var dn = new DistinguishedName("CN=Julian,CN=Users,DC=example,DC=#636f6d");

            // Act

            // Assert
            Assert.Equal("CN=Julian,CN=Users,DC=example,DC=com", dn.ToString());
        }
Exemple #15
0
        public void Child_Should_BuildCorrectDistinguishedName()
        {
            // Arrange
            var fullDN = new DistinguishedName("OU=Users,OU=HDQRK,DC=example,DC=com");
            var baseDN = new DistinguishedName("DC=example,DC=com");

            // Act
            var childDN = baseDN.Child("OU=Users,OU=HDQRK");

            // Assert
            Assert.Equal(fullDN.ToString(), childDN.ToString());
        }
        public void DistinguishedName_OIDs()
        {
            string dnStr1 = @"OID.3.43.128=John";
            string dnStr2 = @"3.43.128=John";
            var    dn1    = new DistinguishedName(dnStr1);
            var    dn2    = new DistinguishedName(dnStr2);

            Assert.AreEqual(dn1.ToString(), dnStr1);
            Assert.AreEqual(dn1.Components.Count, 1);
            Assert.AreEqual(dn2.ToString(), dnStr2);
            Assert.AreEqual(dn2.Components.Count, 1);
        }
        public static X509Certificate2 IssueCertificate(
            string basename,
            string password,
            DistinguishedName dn,
            CertificateType certtype,
            DateTime notBefore,
            DateTime notAfter)
        {
            var certificateGenerator = new X509V3CertificateGenerator();
            var privateOutputPath    = "";
            var publicOutputPath     = "";

            /* Prepare output directories  */
            if (certtype == CertificateType.AuthorityCertificate)
            {
                privateOutputPath = AuthorityPrivateCertificatesPath;
                publicOutputPath  = AuthorityPublicCertificatesPath;
            }
            else if (certtype == CertificateType.ServerCertificate)
            {
                privateOutputPath = ServerPrivateCertificatesPath;
                publicOutputPath  = ServerPublicCertificatesPath;
            }
            else
            {
                privateOutputPath = UserPrivateCertificatesPath;
                publicOutputPath  = UserPublicCertificatesPath;
            }

            /* Certificate Asymmetric Keys */
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            /* Certificate Serial Number */
            BigInteger serialNumber =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            /* Certificate Date Constrains */
            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            /* Certificate Issuer and Subject DN */
            string issuerName = IssuerDN.ToString();

            if (certtype == CertificateType.AuthorityCertificate)
            {
                /* A Certification Authority is a self signed certificate */
                issuerName = dn.ToString();
            }

            certificateGenerator.SetSubjectDN(new X509Name(dn.ToString()));
            certificateGenerator.SetIssuerDN(new X509Name(issuerName));

            /* Certificate Alternative Names */
            if (dn.AlternativeNames != null && dn.AlternativeNames.Any())
            {
                var subjectAlternativeNamesExtension =
                    new DerSequence(
                        dn.AlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
                        .ToArray <Asn1Encodable> ());

                certificateGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }

            /* Certificate Keys Usage  */
            var keyUsageFlags = KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment |
                                KeyUsage.DataEncipherment | KeyUsage.DigitalSignature;

            if (certtype == CertificateType.AuthorityCertificate || certtype == CertificateType.ServerCertificate)
            {
                keyUsageFlags |= KeyUsage.CrlSign | KeyUsage.NonRepudiation;
            }

            certificateGenerator.AddExtension(
                X509Extensions.KeyUsage.Id, false, new KeyUsage(keyUsageFlags));

            /* Certificate Extended Key Usages */
            if (certtype != CertificateType.AuthorityCertificate)
            {
                KeyPurposeID[] extendedUsages = null;

                if (certtype == CertificateType.ServerCertificate)
                {
                    extendedUsages = new KeyPurposeID[] {
                        KeyPurposeID.IdKPServerAuth,
                    };
                }
                else
                {
                    extendedUsages = new KeyPurposeID[] {
                        KeyPurposeID.IdKPClientAuth,
                        KeyPurposeID.IdKPEmailProtection,
                    };
                }

                certificateGenerator.AddExtension(
                    X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedUsages));
            }

            /* Certificate Authority Key Identifier */
            /* A Certification Authority is a self signed certificate */
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;;

            if (certtype != CertificateType.AuthorityCertificate)
            {
                issuerKeyPair = DotNetUtilities.GetKeyPair(IssuerCertificate.PrivateKey);
            }

            var issuerPKIFactory = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public);
            var generalNames     = new GeneralNames(
                new GeneralName(new X509Name(issuerName)));

            /* A Certification Authority is a self signed certificate */
            BigInteger issuerSerialNumber = serialNumber;

            if (certtype != CertificateType.AuthorityCertificate)
            {
                issuerSerialNumber = new BigInteger(IssuerCertificate.GetSerialNumber());
            }

            var authorityKIExtension =
                new AuthorityKeyIdentifier(
                    issuerPKIFactory, generalNames, issuerSerialNumber);

            certificateGenerator.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKIExtension);

            /* Certificate Subject Key Identifier */
            var subjectPKIFactory  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public);
            var subjectKIExtension = new SubjectKeyIdentifier(subjectPKIFactory);

            certificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id, false, subjectKIExtension);

            /* Certificate Basic constrains */
            bool isCertificateAuthority = false;

            if (certtype == CertificateType.AuthorityCertificate)
            {
                isCertificateAuthority = true;
            }

            var basicConstrains = new BasicConstraints(isCertificateAuthority);

            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, basicConstrains);

            /* Generate BouncyCastle Certificate */
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(
                "SHA512WITHRSA",
                issuerKeyPair.Private,
                random
                );

            /* Generate P12 Certificate Store and write to disk*/
            var store = new Pkcs12Store();

            var certificate      = certificateGenerator.Generate(signatureFactory);
            var certificateEntry = new X509CertificateEntry(certificate);
            var stream           = new MemoryStream();

            store.SetCertificateEntry(dn.ToString(), certificateEntry);
            store.SetKeyEntry(dn.ToString(), new AsymmetricKeyEntry(subjectKeyPair.Private), new [] { certificateEntry });
            store.Save(stream, password.ToCharArray(), random);

            File.WriteAllBytes(privateOutputPath + basename + ".p12", stream.ToArray());

            /* Convert to Microsoft X509Certificate2 and write to disk pfx and der files */
            var convertedCertificate =
                new X509Certificate2(stream.ToArray(),
                                     password,
                                     X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            File.WriteAllBytes(privateOutputPath + basename + ".pfx", convertedCertificate.Export(X509ContentType.Pfx, password));
            File.WriteAllBytes(publicOutputPath + basename + ".crt", convertedCertificate.Export(X509ContentType.Cert, password));

            return(convertedCertificate);
        }
        public void DistinguishedName_HexEncodedBinaryValueEnd()
        {
            var dn = new DistinguishedName("CN=John,OU=Employees,DC=adatum,DC=#324312af34e4");

            Assert.AreEqual(dn.ToString(), "CN=John,OU=Employees,DC=adatum,DC=#324312af34e4");
        }
        public void DistinguishedName_HexEncodedBinaryValueMiddle()
        {
            var dn = new DistinguishedName("CN=John,OU=#324312af34e4,DC=adatum,DC=com");

            Assert.AreEqual(dn.ToString(), "CN=John,OU=#324312af34e4,DC=adatum,DC=com");
        }
        public void DistinguishedName_HexEncodedBinaryValueSingle()
        {
            var dn = new DistinguishedName("CN=#324312af34e4");

            Assert.AreEqual(dn.ToString(), "CN=#324312af34e4");
        }
        public void DistinguishedName_Empty()
        {
            var dn = new DistinguishedName(String.Empty);

            Assert.AreEqual(dn.ToString(), String.Empty);
        }
        public void DistinguishedName_LongSpaces()
        {
            var dn = new DistinguishedName(@"    CN     =    John  , OU =  Employees,DC   =    adatum,DC = com");

            Assert.AreEqual(dn.ToString(), "CN=John,OU=Employees,DC=adatum,DC=com");
        }
        public void DistinguishedName_EscapedSpecialChars()
        {
            var dn = new DistinguishedName(@"OU=""\,\=\+\<\>\#\;\\\ """);

            Assert.AreEqual(dn.ToString(), @"OU=\,\=\+\<\>\#\;\\\ ");
        }
        public void DistinguishedName_QuotesEnd()
        {
            var dn = new DistinguishedName(@"OU=John,OU=is,OU=""cool""");

            Assert.AreEqual(dn.ToString(), "OU=John,OU=is,OU=cool");
        }
        public void DistinguishedName_QuotesSingle()
        {
            var dn = new DistinguishedName(@"OU=""John is cool""");

            Assert.AreEqual(dn.ToString(), "OU=John is cool");
        }
        public void DistinguishedName_HexEscapeNonSpecialCharacter()
        {
            var dn = new DistinguishedName(@"CN=John\20Doe,OU=Employees,DC=adatum,DC=com");

            Assert.AreEqual(dn.ToString(), @"CN=John Doe,OU=Employees,DC=adatum,DC=com");
        }
        public void DistinguishedName_SpacesAtBeginningAndEnd()
        {
            var dn = new DistinguishedName(@"CN=\     John    \ ");

            Assert.AreEqual(dn.ToString(), @"CN=\     John    \ ");
        }
Exemple #28
0
        /// <summary>
        /// Creates a self-signed cert.
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="notAfter"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        /// <remarks>
        /// https://blogs.msdn.microsoft.com/alejacma/2008/09/05/how-to-create-a-certificate-request-with-certenroll-and-net-c/
        /// http://stackoverflow.com/questions/13806299/how-to-create-a-self-signed-certificate-using-c
        /// https://technet.microsoft.com/es-es/aa379410
        /// </remarks>
        public static X509Certificate2 CreateSelfSignedCert(DistinguishedName subject, DateTime notAfter, String pwd)
        {
            var cn = new CX500DistinguishedName();

            cn.Encode(subject.ToString(), X500NameFlags.XCN_CERT_NAME_STR_SEMICOLON_FLAG);

            var privateKey = new CX509PrivateKey
            {
                ContainerNamePrefix = "nf-",
                ProviderName        = MS_CRYPTO_PROV_NAME,
                MachineContext      = false,
                Length       = 2048,
                KeySpec      = X509KeySpec.XCN_AT_KEYEXCHANGE,
                ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG
            };

            privateKey.Create();

            var hashobj = new CObjectId();

            hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
                                                ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone,
                                                RSAPKCS1SHA512SigDesc.SHA_512);

            var keyUsage = new CX509ExtensionKeyUsage();

            keyUsage.InitializeEncode(X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE |
                                      X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE);

            //add extended key usage
            var serverAuth = new CObjectId();

            serverAuth.InitializeFromValue("1.3.6.1.5.5.7.3.1");

            var clientAuth = new CObjectId();

            clientAuth.InitializeFromValue("1.3.6.1.5.5.7.3.2");

            var fileCrypt = new CObjectId();

            fileCrypt.InitializeFromValue("1.3.6.1.4.1.311.10.3.4");

            var docSign = new CObjectId();

            docSign.InitializeFromValue("1.3.6.1.4.1.311.10.3.12");

            var oidList = new CObjectIds {
                serverAuth, fileCrypt, docSign
            };
            var eku = new CX509ExtensionEnhancedKeyUsage();

            eku.InitializeEncode(oidList);

            var cert = new CX509CertificateRequestCertificate();

            cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, "");
            cert.Subject   = cn;
            cert.Issuer    = cn;
            cert.NotBefore = DateTime.Now;
            cert.NotAfter  = notAfter;
            cert.X509Extensions.Add((CX509Extension)keyUsage);
            cert.X509Extensions.Add((CX509Extension)eku);
            cert.HashAlgorithm = hashobj;
            cert.Encode();

            var enroll = new CX509Enrollment();

            enroll.InitializeFromRequest(cert);
            enroll.CertificateFriendlyName = subject.CommonName;

            var csr = enroll.CreateRequest();

            enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedRoot, csr,
                                   EncodingType.XCN_CRYPT_STRING_BASE64, pwd);

            var b64Encode = enroll.CreatePFX(pwd, PFXExportOptions.PFXExportEEOnly);

            var managedX509Cert = new X509Certificate2(Convert.FromBase64String(b64Encode), pwd,
                                                       X509KeyStorageFlags.Exportable);

            return(managedX509Cert);
        }