Example #1
0
        public void Certificate_CSR_AddressBound()
        {
            X500DistinguishedName   dn      = new X500DistinguishedName("[email protected],o=TNT,c=US");
            AsymmetricCipherKeyPair keyPair = Certificate.CreateRSAKeyPair();
            Extensions extensions           = new Extensions();

            extensions.Add(new TNT.Cryptography.Extension.KeyUsage(KeyUsage.KeyEncipherment | KeyUsage.DigitalSignature));
            extensions.Add(new TNT.Cryptography.Extension.SubjectAlternativeName(new GeneralName(GeneralName.Rfc822Name, dn.Name.Split(',')[0].Split('=')[1])));
            extensions.Add(new TNT.Cryptography.Extension.ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection));
            extensions.Add(new TNT.Cryptography.Extension.AuthorityKeyIdentifier(TA));
            extensions.Add(new TNT.Cryptography.Extension.SubjectKeyIdentifier(keyPair.Public));
            extensions.Add(new TNT.Cryptography.Extension.BasicConstraints(new BasicConstraints(false)));
            List <Uri> uris = new List <Uri>(new Uri[] { new Uri("http://domain1.com"), new Uri("http://domain2.com") });

            extensions.Add(new TNT.Cryptography.Extension.CrlDistributionPoints(uris));

            Pkcs10CertificationRequest csr  = Certificate.CreateCertificationRequest(dn.Name, keyPair, extensions);
            X509Certificate2           cert = Certificate.CreateCertificate(csr, keyPair, m_EffectiveDate, m_ExpirationDate, TA);

            System.Security.Cryptography.X509Certificates.X509Extension ski = TA.Extensions[1];
            System.Security.Cryptography.X509Certificates.X509Extension aki = cert.Extensions[3];

            Assert.AreEqual("CN=Trust Anchor, O=TNT, C=US", cert.Issuer);
            Assert.AreEqual("C=US, O=TNT, [email protected]", cert.Subject);

            var skiCount = ski.Format(false).Length;

            Assert.AreEqual(ski.Format(false), aki.Format(false).Substring(6, skiCount));

            File.WriteAllBytes("CSR_AddressBound.cer", cert.Export(X509ContentType.Cert));
        }
Example #2
0
        public void Certificate_CSR_TA_SelfSigned()
        {
            X500DistinguishedName   dn      = new X500DistinguishedName("CN=Secondary Trust Anchor,O=TNT,C=US");
            AsymmetricCipherKeyPair keyPair = Certificate.CreateRSAKeyPair();
            Extensions extensions           = new Extensions();

            extensions.Add(new TNT.Cryptography.Extension.KeyUsage(KeyUsage.CrlSign | KeyUsage.KeyCertSign | KeyUsage.DigitalSignature));
            extensions.Add(new TNT.Cryptography.Extension.AuthorityKeyIdentifier(keyPair.Public));
            extensions.Add(new TNT.Cryptography.Extension.SubjectKeyIdentifier(keyPair.Public));
            extensions.Add(new TNT.Cryptography.Extension.BasicConstraints(new BasicConstraints(0)));
            List <Uri> uris = new List <Uri>(new Uri[] { new Uri("http://domain1.com"), new Uri("http://domain2.com") });

            extensions.Add(new TNT.Cryptography.Extension.CrlDistributionPoints(uris));

            Pkcs10CertificationRequest csr  = Certificate.CreateCertificationRequest(dn.Name, keyPair, extensions);
            X509Certificate2           cert = Certificate.CreateCertificate(csr, keyPair, m_EffectiveDate, m_ExpirationDate, null);

            X509KeyUsageExtension         keyUsageEx        = cert.Extensions[0] as X509KeyUsageExtension;
            X509BasicConstraintsExtension basicConstraintEx = cert.Extensions[3] as X509BasicConstraintsExtension;

            System.Security.Cryptography.X509Certificates.X509Extension aki = cert.Extensions[1];
            System.Security.Cryptography.X509Certificates.X509Extension ski = cert.Extensions[2];

            Assert.AreEqual(X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.DigitalSignature, keyUsageEx.KeyUsages);
            Assert.IsTrue(basicConstraintEx.CertificateAuthority);
            Assert.AreEqual("C=US, O=TNT, CN=Secondary Trust Anchor", cert.Subject);
            Assert.AreEqual(cert.Subject, cert.Issuer);

            var skiCount = ski.Format(false).Length;

            Assert.AreEqual(ski.Format(false), aki.Format(false).Substring(6, skiCount));

            File.WriteAllBytes("CSR_TA_SS.cer", cert.Export(X509ContentType.Cert));
            File.WriteAllBytes("CSR_TA_SS.pfx", cert.Export(X509ContentType.Pfx, "P"));
        }
Example #3
0
        public void Certificate_CSR_SelfSigned_DomainBound()
        {
            X500DistinguishedName   dn      = new X500DistinguishedName("cn=domain.com,o=TNT,c=US");
            AsymmetricCipherKeyPair keyPair = Certificate.CreateRSAKeyPair();
            Extensions extensions           = new Extensions();

            extensions.Add(new TNT.Cryptography.Extension.KeyUsage(KeyUsage.KeyEncipherment | KeyUsage.DigitalSignature));
            extensions.Add(new TNT.Cryptography.Extension.SubjectAlternativeName(new GeneralName(GeneralName.DnsName, dn.Name.Split(',')[0].Split('=')[1])));
            extensions.Add(new TNT.Cryptography.Extension.ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection));
            extensions.Add(new TNT.Cryptography.Extension.SubjectKeyIdentifier(keyPair.Public));
            extensions.Add(new TNT.Cryptography.Extension.BasicConstraints(new BasicConstraints(false)));
            List <Uri> uris = new List <Uri>(new Uri[] { new Uri("http://domain1.com"), new Uri("http://domain2.com") });

            extensions.Add(new TNT.Cryptography.Extension.CrlDistributionPoints(uris));

            Pkcs10CertificationRequest csr  = Certificate.CreateCertificationRequest(dn.Name, keyPair, extensions);
            X509Certificate2           cert = Certificate.CreateCertificate(csr, keyPair, m_EffectiveDate, m_ExpirationDate);

            System.Security.Cryptography.X509Certificates.X509Extension subAltNameEx = cert.Extensions[1];
            X509EnhancedKeyUsageExtension enhancedKUEx      = cert.Extensions[2] as X509EnhancedKeyUsageExtension;
            X509BasicConstraintsExtension basicConstraintEx = cert.Extensions[4] as X509BasicConstraintsExtension;

            enhancedKUEx = cert.GetEnhancedKeyUsage();

            Assert.AreEqual("DNS Name=domain.com", subAltNameEx.Format(false));
            Assert.AreEqual(KeyPurposeID.IdKPEmailProtection.Id, enhancedKUEx.EnhancedKeyUsages[0].Value);
            Assert.IsFalse(basicConstraintEx.CertificateAuthority);
            Assert.AreEqual("C=US, O=TNT, CN=domain.com", cert.Issuer);
            Assert.AreEqual("C=US, O=TNT, CN=domain.com", cert.Subject);

            File.WriteAllBytes("CSR_SelfSigned_DomainBound.cer", cert.Export(X509ContentType.Cert));
        }
Example #4
0
        /// <summary>
        /// Returns a formatted version of the Abstract Syntax Notation One (ASN.1)-encoded data as a string.
        /// </summary>
        /// <param name="multiLine"><strong>True</strong> if the return string should contain carriage returns; otherwise, <strong>False</strong>.</param>
        /// <returns>A formatted string that represents the Abstract Syntax Notation One (ASN.1)-encoded data.</returns>
        public override String Format(Boolean multiLine)
        {
            StringBuilder SB = new StringBuilder();

            SB.Append("[0]Certificate issuer: ");
            if (multiLine)
            {
                SB.Append(Environment.NewLine + "     ");
            }
            SB.Append(IssuerName);
            if (multiLine)
            {
                SB.Append(Environment.NewLine);
            }
            if (AIARaw.Length > 1)
            {
                if (!multiLine)
                {
                    SB.Append(", ");
                }
                X509Extension aia = new X509Extension(new Oid(X509CertExtensions.X509AuthorityInformationAccess), AIARaw, false);
                SB.Append(aia.Format(multiLine));
            }
            return(SB.ToString());
        }
            // static initializer runs only when one of the properties is accessed
            static X509SubjectAlternativeNameConstants()
            {
                // Extracted a well-known X509Extension
                byte[] x509ExtensionBytes = new byte[] {
                    48, 36, 130, 21, 110, 111, 116, 45, 114, 101, 97, 108, 45, 115, 117, 98, 106, 101, 99,
                    116, 45, 110, 97, 109, 101, 130, 11, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109
                };
                const string subjectName1 = "not-real-subject-name";

                try
                {
                    X509Extension x509Extension = new X509Extension(Oid, x509ExtensionBytes, true);
                    string x509ExtensionFormattedString = x509Extension.Format(false);

                    // Each OS has a different dNSName identifier and delimiter
                    // On Windows, dNSName == "DNS Name" (localizable), on Linux, dNSName == "DNS"
                    // e.g.,
                    // Windows: x509ExtensionFormattedString is: "DNS Name=not-real-subject-name, DNS Name=example.com"
                    // Linux:   x509ExtensionFormattedString is: "DNS:not-real-subject-name, DNS:example.com"
                    // Parse: <identifier><delimter><value><separator(s)>

                    int delimiterIndex = x509ExtensionFormattedString.IndexOf(subjectName1) - 1;
                    _delimiter = x509ExtensionFormattedString[delimiterIndex];

                    // Make an assumption that all characters from the the start of string to the delimiter 
                    // are part of the identifier
                    _identifier = x509ExtensionFormattedString.Substring(0, delimiterIndex);

                    int separatorFirstChar = delimiterIndex + subjectName1.Length + 1;
                    int separatorLength = 1;
                    for (int i = separatorFirstChar + 1; i < x509ExtensionFormattedString.Length; i++)
                    {
                        // We advance until the first character of the identifier to determine what the
                        // separator is. This assumes that the identifier assumption above is correct
                        if (x509ExtensionFormattedString[i] == _identifier[0])
                        {
                            break;
                        }
                        
                        separatorLength++;
                    }

                    _separator = x509ExtensionFormattedString.Substring(separatorFirstChar, separatorLength);

                    _successfullyInitialized = true;
                }
                catch (Exception ex)
                {
                    _successfullyInitialized = false;
                    _initializationException = ex;
                }
            }
Example #6
0
		public void ConstructorAsnEncodedData_BadAsn ()
		{
			AsnEncodedData aed = new AsnEncodedData ("1.2.3", new byte[0]);
			X509Extension ex = new X509Extension (aed, true);
			Assert.AreEqual (String.Empty, ex.Format (true), "Format(true)");
			Assert.AreEqual (String.Empty, ex.Format (false), "Format(false)");
			// no exception for an "empty" extension
		}
Example #7
0
		public void ConstructorAsnEncodedData_BadAsnTag ()
		{
			AsnEncodedData aed = new AsnEncodedData ("1.2.3", new byte[] { 0x05, 0x00 });
			X509Extension ex = new X509Extension (aed, true);
			Assert.AreEqual ("05 00", ex.Format (true), "Format(true)");
			Assert.AreEqual ("05 00", ex.Format (false), "Format(false)");
			// no exception for an "unknown" (ASN.1 NULL) extension
		}
Example #8
0
		public void ConstructorAsnEncodedData_BadAsnLength ()
		{
			AsnEncodedData aed = new AsnEncodedData ("1.2.3", new byte[] { 0x30, 0x01 });
			X509Extension ex = new X509Extension (aed, true);
			Assert.AreEqual ("30 01", ex.Format (true), "Format(true)");
			Assert.AreEqual ("30 01", ex.Format (false), "Format(false)");
			// no exception for an bad (invalid length) extension
		}
            // static initializer runs only when one of the properties is accessed
            static X509SubjectAlternativeNameConstants()
            {
                // Extracted a well-known X509Extension
                const string x509ExtensionBase64String = "MCSCFW5vdC1yZWFsLXN1YmplY3QtbmFtZYILZXhhbXBsZS5jb20=";
                const string subjectName1 = "not-real-subject-name";

                X509Extension x509Extension = new X509Extension(Oid, Convert.FromBase64String(x509ExtensionBase64String), true);
                string x509ExtensionFormattedString = x509Extension.Format(false);

                // Each OS has a different dNSName identifier and delimiter
                // On Windows, dNSName == "DNS Name" (localizable), on Linux, dNSName == "DNS"
                // e.g.,
                // Windows: x509ExtensionFormattedString is: "DNS Name=not-real-subject-name, DNS Name=example.com"
                // Linux:   x509ExtensionFormattedString is: "DNS:not-real-subject-name, DNS:example.com"
                // Parse: <identifier><delimter><value><separator(s)>

                int delimiterIndex = x509ExtensionFormattedString.IndexOf(subjectName1) - 1;
                Delimiter = x509ExtensionFormattedString[delimiterIndex];

                // Make an assumption that all characters from the the start of string to the delimiter 
                // are part of the identifier
                Identifier = x509ExtensionFormattedString.Substring(0, delimiterIndex);

                int separatorFirstChar = delimiterIndex + subjectName1.Length + 1;
                int separatorLength = 1;
                for (int i = separatorFirstChar + 1; i < x509ExtensionFormattedString.Length; i++)
                {
                    // We advance until the first character of the identifier to determine what the
                    // separator is. This assumes that the identifier assumption above is correct
                    if (x509ExtensionFormattedString[i] == Identifier[0])
                    {
                        break;
                    }
                    else
                    {
                        separatorLength++;
                    }
                }

                Separator = x509ExtensionFormattedString.Substring(separatorFirstChar, separatorLength);
            }
        public override string ToString(bool verbose)
        {
            if (!verbose || this.m_safeCertContext.IsInvalid)
            {
                return(this.ToString());
            }
            StringBuilder sb = new StringBuilder();

            sb.Append("[Version]" + Environment.NewLine + "  ");
            sb.Append("V" + this.Version);
            sb.Append(Environment.NewLine + Environment.NewLine + "[Subject]" + Environment.NewLine + "  ");
            sb.Append(this.SubjectName.Name);
            string nameInfo = this.GetNameInfo(X509NameType.SimpleName, false);

            if (nameInfo.Length > 0)
            {
                sb.Append(Environment.NewLine + "  Simple Name: ");
                sb.Append(nameInfo);
            }
            string str2 = this.GetNameInfo(X509NameType.EmailName, false);

            if (str2.Length > 0)
            {
                sb.Append(Environment.NewLine + "  Email Name: ");
                sb.Append(str2);
            }
            string str3 = this.GetNameInfo(X509NameType.UpnName, false);

            if (str3.Length > 0)
            {
                sb.Append(Environment.NewLine + "  UPN Name: ");
                sb.Append(str3);
            }
            string str4 = this.GetNameInfo(X509NameType.DnsName, false);

            if (str4.Length > 0)
            {
                sb.Append(Environment.NewLine + "  DNS Name: ");
                sb.Append(str4);
            }
            sb.Append(Environment.NewLine + Environment.NewLine + "[Issuer]" + Environment.NewLine + "  ");
            sb.Append(this.IssuerName.Name);
            nameInfo = this.GetNameInfo(X509NameType.SimpleName, true);
            if (nameInfo.Length > 0)
            {
                sb.Append(Environment.NewLine + "  Simple Name: ");
                sb.Append(nameInfo);
            }
            str2 = this.GetNameInfo(X509NameType.EmailName, true);
            if (str2.Length > 0)
            {
                sb.Append(Environment.NewLine + "  Email Name: ");
                sb.Append(str2);
            }
            str3 = this.GetNameInfo(X509NameType.UpnName, true);
            if (str3.Length > 0)
            {
                sb.Append(Environment.NewLine + "  UPN Name: ");
                sb.Append(str3);
            }
            str4 = this.GetNameInfo(X509NameType.DnsName, true);
            if (str4.Length > 0)
            {
                sb.Append(Environment.NewLine + "  DNS Name: ");
                sb.Append(str4);
            }
            sb.Append(Environment.NewLine + Environment.NewLine + "[Serial Number]" + Environment.NewLine + "  ");
            sb.Append(this.SerialNumber);
            sb.Append(Environment.NewLine + Environment.NewLine + "[Not Before]" + Environment.NewLine + "  ");
            sb.Append(X509Certificate.FormatDate(this.NotBefore));
            sb.Append(Environment.NewLine + Environment.NewLine + "[Not After]" + Environment.NewLine + "  ");
            sb.Append(X509Certificate.FormatDate(this.NotAfter));
            sb.Append(Environment.NewLine + Environment.NewLine + "[Thumbprint]" + Environment.NewLine + "  ");
            sb.Append(this.Thumbprint);
            sb.Append(Environment.NewLine + Environment.NewLine + "[Signature Algorithm]" + Environment.NewLine + "  ");
            sb.Append(this.SignatureAlgorithm.FriendlyName + "(" + this.SignatureAlgorithm.Value + ")");
            System.Security.Cryptography.X509Certificates.PublicKey publicKey = this.PublicKey;
            sb.Append(Environment.NewLine + Environment.NewLine + "[Public Key]" + Environment.NewLine + "  Algorithm: ");
            sb.Append(publicKey.Oid.FriendlyName);
            sb.Append(Environment.NewLine + "  Length: ");
            sb.Append(publicKey.Key.KeySize);
            sb.Append(Environment.NewLine + "  Key Blob: ");
            sb.Append(publicKey.EncodedKeyValue.Format(true));
            sb.Append(Environment.NewLine + "  Parameters: ");
            sb.Append(publicKey.EncodedParameters.Format(true));
            this.AppendPrivateKeyInfo(sb);
            X509ExtensionCollection extensions = this.Extensions;

            if (extensions.Count > 0)
            {
                sb.Append(Environment.NewLine + Environment.NewLine + "[Extensions]");
                X509ExtensionEnumerator enumerator = extensions.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    X509Extension current = enumerator.Current;
                    sb.Append(Environment.NewLine + "* " + current.Oid.FriendlyName + "(" + current.Oid.Value + "):" + Environment.NewLine + "  " + current.Format(true));
                }
            }
            sb.Append(Environment.NewLine);
            return(sb.ToString());
        }
            // static initializer will run before properties are accessed
            static X509SubjectAlternativeNameConstants()
            {
                // Extracted a well-known X509Extension
                byte[] x509ExtensionBytes = new byte[] {
                    48, 36, 130, 21, 110, 111, 116, 45, 114, 101, 97, 108, 45, 115, 117, 98, 106, 101, 99,
                    116, 45, 110, 97, 109, 101, 130, 11, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109
                };
                const string subjectName = "not-real-subject-name";
                string x509ExtensionFormattedString = string.Empty;
                try
                {
                    X509Extension x509Extension = new X509Extension(SanOid, x509ExtensionBytes, true);
                    x509ExtensionFormattedString = x509Extension.Format(false);

                    // Each OS has a different dNSName identifier and delimiter
                    // On Windows, dNSName == "DNS Name" (localizable), on Linux, dNSName == "DNS"
                    // e.g.,
                    // Windows: x509ExtensionFormattedString is: "DNS Name=not-real-subject-name, DNS Name=example.com"
                    // Linux:   x509ExtensionFormattedString is: "DNS:not-real-subject-name, DNS:example.com"
                    // Parse: <identifier><delimiter><value><separator(s)>

                    int delimiterIndex = x509ExtensionFormattedString.IndexOf(subjectName) - 1;
                    Delimiter = x509ExtensionFormattedString[delimiterIndex];

                    // Make an assumption that all characters from the the start of string to the delimiter 
                    // are part of the identifier
                    Identifier = x509ExtensionFormattedString.Substring(0, delimiterIndex);

                    int separatorFirstChar = delimiterIndex + subjectName.Length + 1;
                    int separatorLength = 1;
                    for (int i = separatorFirstChar + 1; i < x509ExtensionFormattedString.Length; i++)
                    {
                        // We advance until the first character of the identifier to determine what the
                        // separator is. This assumes that the identifier assumption above is correct
                        if (x509ExtensionFormattedString[i] == Identifier[0])
                        {
                            break;
                        }

                        separatorLength++;
                    }

                    Separator = x509ExtensionFormattedString.Substring(separatorFirstChar, separatorLength);
                    SeparatorArray = new string[1] { Separator };
                    SuccessfullyInitialized = true;
                }
                catch (Exception ex)
                {
                    SuccessfullyInitialized = false;                    
                    DiagnosticUtility.TraceHandledException(
                        new FormatException(string.Format(CultureInfo.InvariantCulture,
                        "There was an error parsing the SubjectAlternativeNames: '{0}'. See inner exception for more details.{1}Detected values were: Identifier: '{2}'; Delimiter:'{3}'; Separator:'{4}'",
                        x509ExtensionFormattedString,
                        Environment.NewLine,
                        Identifier,
                        Delimiter,
                        Separator),
                        ex), 
                        TraceEventType.Warning);
                }
            }
		public void ConstructorAsnEncodedData ()
		{
			AsnEncodedData aed = new AsnEncodedData (new Oid ("2.5.29.37"), new byte[] { 0x30, 0x05, 0x06, 0x03, 0x2A, 0x03, 0x04 });
			X509Extension ex = new X509Extension (aed, true);
			Assert.IsTrue (ex.Critical, "Critical");
			Assert.AreEqual (7, ex.RawData.Length, "RawData");	// original Oid ignored
			Assert.AreEqual ("2.5.29.37", ex.Oid.Value, "Oid.Value");
			Assert.AreEqual ("Enhanced Key Usage", ex.Oid.FriendlyName, "Oid.FriendlyName");
			Assert.AreEqual ("Unknown Key Usage (1.2.3.4)" + Environment.NewLine, ex.Format (true), "Format(true)");
			Assert.AreEqual ("Unknown Key Usage (1.2.3.4)", ex.Format (false), "Format(false)");
		}
		public void Build_NetscapeCertTypeExtension ()
		{
			X509Extension ex = new X509Extension (new Oid ("2.16.840.1.113730.1.1"), new byte[] { 0x03, 0x02, 0x00, 0xFF }, false);
			// strangely no NewLine is being appended to Format(true)
			Assert.AreEqual ("SSL Client Authentication, SSL Server Authentication, SMIME, Signature, Unknown cert type, SSL CA, SMIME CA, Signature CA (ff)", ex.Format (true), "aed.Format(true)");
			Assert.AreEqual ("SSL Client Authentication, SSL Server Authentication, SMIME, Signature, Unknown cert type, SSL CA, SMIME CA, Signature CA (ff)", ex.Format (false), "aed.Format(false)");
		}