Inheritance: System.Security.Cryptography.AsnEncodedData
Ejemplo n.º 1
0
 public int Add(X509Extension extension)
 {
     if (extension == null)
         throw new ArgumentNullException("extension");
     _list.Add(extension);
     return _list.Count - 1;
 }
Ejemplo n.º 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"));
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 4
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));
        }
 public int Add(X509Extension extension)
 {
     if (extension == null)
     {
         throw new ArgumentNullException("extension");
     }
     return this.m_list.Add(extension);
 }
		public void CopyTo (X509Extension[] array, int index) 
		{
			if (array == null)
				throw new ArgumentNullException ("array");
			if (index < 0)
				throw new ArgumentException ("negative index");
			if (index > array.Length)
				throw new ArgumentOutOfRangeException ("index > array.Length");
		}
		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 MarshalX509Extension(X509Extension extension)
 {
     _extension = extension;
     _blobPtr = Marshal.AllocHGlobal(extension.RawData.Length);
     Marshal.Copy(extension.RawData, 0, _blobPtr, extension.RawData.Length);
     var blob = new CRYPT_OBJID_BLOB();
     blob.cbData = (uint)extension.RawData.Length;
     blob.pbData = _blobPtr;
     var nativeExtension = new CERT_EXTENSION();
     nativeExtension.fCritical = extension.Critical;
     nativeExtension.pszObjId = extension.Oid.Value;
     nativeExtension.Value = blob;
     _value = nativeExtension;
 }
Ejemplo n.º 9
0
            private static bool CheckCertificateUsage(X509Certificate2 cert)
            {
                try
                {
                    if (cert.Version < 3)
                    {
                        return(true);
                    }
                    X509KeyUsageExtension         x509KeyUsageExtension         = (X509KeyUsageExtension)cert.Extensions["2.5.29.15"];
                    X509EnhancedKeyUsageExtension x509EnhancedKeyUsageExtension = (X509EnhancedKeyUsageExtension)cert.Extensions["2.5.29.37"];
                    if (x509KeyUsageExtension != null && x509EnhancedKeyUsageExtension != null)
                    {
                        if ((x509KeyUsageExtension.KeyUsages & s_flags) == X509KeyUsageFlags.None)
                        {
                            return(false);
                        }
                        return(x509EnhancedKeyUsageExtension.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] != null || x509EnhancedKeyUsageExtension.EnhancedKeyUsages["2.16.840.1.113730.4.1"] != null);
                    }
                    if (x509KeyUsageExtension != null)
                    {
                        return((x509KeyUsageExtension.KeyUsages & s_flags) != X509KeyUsageFlags.None);
                    }
                    if (x509EnhancedKeyUsageExtension != null)
                    {
                        return(x509EnhancedKeyUsageExtension.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] != null || x509EnhancedKeyUsageExtension.EnhancedKeyUsages["2.16.840.1.113730.4.1"] != null);
                    }
                    System.Security.Cryptography.X509Certificates.X509Extension x509Extension = cert.Extensions["2.16.840.1.113730.1.1"];
                    if (x509Extension != null)
                    {
                        string text = x509Extension.NetscapeCertType(multiLine: false);
                        return(text.IndexOf("SSL Server Authentication") != -1);
                    }
                    return(true);

IL_0133:
                    bool result;
                    return(result);
                }
                catch (Exception arg)
                {
                    Console.Error.WriteLine("ERROR processing certificate: {0}", arg);
                    Console.Error.WriteLine("Please, report this problem to the Mono team");
                    return(false);

IL_0162:
                    bool result;
                    return(result);
                }
            }
Ejemplo n.º 10
0
        private static Pkcs10CertificationRequest CreatePKCS10ForComputer(string challengePassword, AsymmetricCipherKeyPair rsaKeyPair)
        {
            //            GenerateSelfSignedCertificate("CN=" + LDAPTools.QuoteRDN(fqdn), out RSA algRSA, out CertificateRequest req, out X509Certificate2 selfSignedCert);

            AsnX509.X509ExtensionsGenerator extensions = new AsnX509.X509ExtensionsGenerator();

            ISet <string> sanDNSCollection = new HashSet <string>(4);

            string hostName = Dns.GetHostName();

            sanDNSCollection.Add(hostName);
            string fqdn = Dns.GetHostEntry(hostName).HostName;

            sanDNSCollection.Add(fqdn);

#if !DEBUG
            Domain computerDomain = Domain.GetComputerDomain();
            sanDNSCollection.Add(computerDomain.Name);

            string NetBIOSDomain = GetNetbiosDomainName(computerDomain.Name);
            if (!string.IsNullOrEmpty(NetBIOSDomain))
            {
                sanDNSCollection.Add(NetBIOSDomain);
            }
#endif // !DEBUG

            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
            foreach (string dnsName in sanDNSCollection)
            {
                sanBuilder.AddDnsName(dnsName);
            }
            System.Security.Cryptography.X509Certificates.X509Extension sanExtension = sanBuilder.Build();
            extensions.AddExtension(new DerObjectIdentifier(sanExtension.Oid.Value), sanExtension.Critical, sanExtension.RawData);

            BCPkcs.AttributePkcs extensionRequest = new BCPkcs.AttributePkcs(BCPkcs.PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(extensions.Generate()));

            BCPkcs.AttributePkcs attrPassword = new BCPkcs.AttributePkcs(BCPkcs.PkcsObjectIdentifiers.Pkcs9AtChallengePassword, new DerSet(new DerPrintableString(challengePassword)));

            Pkcs10CertificationRequest request = new Pkcs10CertificationRequest(
                "SHA256WITHRSA",
                new AsnX509.X509Name(new DerObjectIdentifier[] { AsnX509.X509Name.CN }, new string[] { fqdn }),
                rsaKeyPair.Public,
                new DerSet(extensionRequest, attrPassword),
                rsaKeyPair.Private
                );
            return(request);
        }
 public SafeX509Extension(X509Extension extension)
 {
     this.blobPtr = Marshal.AllocHGlobal(extension.RawData.Length);
     Marshal.Copy(extension.RawData, 0, this.blobPtr, extension.RawData.Length);
     var blob = new CRYPTOAPI_BLOB
     {
         cbData = (uint)extension.RawData.Length,
         pbData = this.blobPtr
     };
     var nativeExtension = new CERT_EXTENSION
     {
         fCritical = extension.Critical,
         pszObjId = extension.Oid.Value,
         Value = blob
     };
     this.value = nativeExtension;
 }
Ejemplo n.º 12
0
    /// <summary>
    /// Return the authority key identifier in the certificate.
    /// </summary>
    private static X509AuthorityKeyIdentifierExtension FindAuthorityKeyIdentifier(X509Certificate2 certificate)
    {
        for (int ii = 0; ii < certificate.Extensions.Count; ii++)
        {
            System.Security.Cryptography.X509Certificates.X509Extension extension = certificate.Extensions[ii];

            switch (extension.Oid.Value)
            {
            case X509AuthorityKeyIdentifierExtension.AuthorityKeyIdentifierOid:
            case X509AuthorityKeyIdentifierExtension.AuthorityKeyIdentifier2Oid:
            {
                return(new X509AuthorityKeyIdentifierExtension(extension, extension.Critical));
            }
            }
        }

        return(null);
    }
 internal unsafe X509ExtensionCollection(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle)
 {
     this.m_list = new ArrayList();
     using (System.Security.Cryptography.SafeCertContextHandle handle = CAPI.CertDuplicateCertificateContext(safeCertContextHandle))
     {
         CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT*) handle.DangerousGetHandle());
         CAPIBase.CERT_INFO cert_info = (CAPIBase.CERT_INFO) Marshal.PtrToStructure(cert_context.pCertInfo, typeof(CAPIBase.CERT_INFO));
         uint cExtension = cert_info.cExtension;
         IntPtr rgExtension = cert_info.rgExtension;
         for (uint i = 0; i < cExtension; i++)
         {
             X509Extension asnEncodedData = new X509Extension(new IntPtr(((long) rgExtension) + (i * Marshal.SizeOf(typeof(CAPIBase.CERT_EXTENSION)))));
             X509Extension extension2 = CryptoConfig.CreateFromName(asnEncodedData.Oid.Value) as X509Extension;
             if (extension2 != null)
             {
                 extension2.CopyFrom(asnEncodedData);
                 asnEncodedData = extension2;
             }
             this.Add(asnEncodedData);
         }
     }
 }
		public void WrongExtension_X509Extension ()
		{
			X509Extension ex = new X509Extension ("1.2.3", new byte [0], true);
			X509KeyUsageExtension ku = new X509KeyUsageExtension (X509KeyUsageFlags.CrlSign, true);
			ku.CopyFrom (ex);
			Assert.IsTrue (ku.Critical, "Critical");
			Assert.AreEqual (String.Empty, BitConverter.ToString (ku.RawData), "RawData");
			Assert.AreEqual ("1.2.3", ku.Oid.Value, "Oid.Value");
			Assert.IsNull (ku.Oid.FriendlyName, "Oid.FriendlyName");
		}
		public void WrongExtension_X509Extension_CertificateAuthority ()
		{
			X509Extension ex = new X509Extension ("1.2.3", new byte[0], true);
			X509BasicConstraintsExtension bc = new X509BasicConstraintsExtension ();
			bc.CopyFrom (ex);
			bool b = bc.CertificateAuthority;
		}
		public void WrongExtension_X509Extension ()
		{
			X509Extension ex = new X509Extension ("1.2.3", new byte[0], true);
			X509BasicConstraintsExtension bc = new X509BasicConstraintsExtension (false, true, 1, false);
			Assert.IsFalse (bc.Critical, "Critical");
			bc.CopyFrom (ex);
			Assert.IsTrue (bc.Critical, "Critical");
			Assert.AreEqual (String.Empty, BitConverter.ToString (bc.RawData), "RawData");
			Assert.AreEqual ("1.2.3", bc.Oid.Value, "Oid.Value");
			Assert.IsNull (bc.Oid.FriendlyName, "Oid.FriendlyName");
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="X509ExtensionWrapper"/> class.
 /// </summary>
 /// <param name="extension">The extension.</param>
 public X509SimpleExtensionWrapper(X509Extension extension)
     : base(extension)
 {
     x509 = extension;
 }
 public static X509ExtensionWrapper Create(X509Extension extension)
 {
     if (extension == null) return null;
     else if (extension is X509BasicConstraintsExtension)
         return new X509BasicConstraintsExtensionWrapper((X509BasicConstraintsExtension)extension);
     else if (extension is X509EnhancedKeyUsageExtension)
         return new X509EnhancedKeyUsageExtensionWrapper((X509EnhancedKeyUsageExtension)extension);
     else if (extension is X509KeyUsageExtension)
         return new X509KeyUsageExtensionWrapper((X509KeyUsageExtension)extension);
     else if (extension is X509SubjectKeyIdentifierExtension)
         return new X509SubjectKeyIdentifierExtensionWrapper((X509SubjectKeyIdentifierExtension)extension);
     else return new X509SimpleExtensionWrapper(extension);
 }
Ejemplo n.º 19
0
		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)
			// FIXME: Don't expect that FriendlyName is English. This test fails under non-English Windows.
			//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)");
		}
Ejemplo n.º 20
0
        /// <summary>
        /// Gets certificate revocation list sequence number.
        /// </summary>
        /// <returns>Certificate revocation list sequence number.</returns>
        /// <remarks>If CRL is X.509 CRL Version 1, or CRL does not contains 'CRL Number' extension, a zero is returned.</remarks>
        public BigInteger GetCRLNumber()
        {
            X509Extension e = _extensions[X509ExtensionOid.CRLNumber];

            return(((X509CRLNumberExtension)e)?.CRLNumber ?? 0);
        }
            private static bool CheckCertificateUsage(System.Security.Cryptography.X509Certificates.X509Certificate2 cert)
            {
                bool result;

                try
                {
                    if (cert.Version < 3)
                    {
                        result = true;
                    }
                    else
                    {
                        System.Security.Cryptography.X509Certificates.X509KeyUsageExtension         x509KeyUsageExtension         = (System.Security.Cryptography.X509Certificates.X509KeyUsageExtension)cert.Extensions["2.5.29.15"];
                        System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension x509EnhancedKeyUsageExtension = (System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension)cert.Extensions["2.5.29.37"];
                        if (x509KeyUsageExtension != null && x509EnhancedKeyUsageExtension != null)
                        {
                            if ((x509KeyUsageExtension.KeyUsages & ServicePointManager.ChainValidationHelper.s_flags) == System.Security.Cryptography.X509Certificates.X509KeyUsageFlags.None)
                            {
                                result = false;
                            }
                            else
                            {
                                result = (x509EnhancedKeyUsageExtension.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] != null || x509EnhancedKeyUsageExtension.EnhancedKeyUsages["2.16.840.1.113730.4.1"] != null);
                            }
                        }
                        else if (x509KeyUsageExtension != null)
                        {
                            result = ((x509KeyUsageExtension.KeyUsages & ServicePointManager.ChainValidationHelper.s_flags) != System.Security.Cryptography.X509Certificates.X509KeyUsageFlags.None);
                        }
                        else if (x509EnhancedKeyUsageExtension != null)
                        {
                            result = (x509EnhancedKeyUsageExtension.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] != null || x509EnhancedKeyUsageExtension.EnhancedKeyUsages["2.16.840.1.113730.4.1"] != null);
                        }
                        else
                        {
                            System.Security.Cryptography.X509Certificates.X509Extension x509Extension = cert.Extensions["2.16.840.1.113730.1.1"];
                            if (x509Extension != null)
                            {
                                string text = x509Extension.NetscapeCertType(false);
                                result = (text.IndexOf("SSL Server Authentication") != -1);
                            }
                            else
                            {
                                result = true;
                            }
                        }
                    }
                }
                catch (Exception arg)
                {
                    Console.Error.WriteLine("ERROR processing certificate: {0}", arg);
                    Console.Error.WriteLine("Please, report this problem to the Mono team");
                    result = false;
                }
                return(result);
            }
Ejemplo n.º 22
0
        private static void ReadCertPolicyConstraintsExtension(X509Extension extension, CertificatePolicy policy)
        {
            DerSequenceReader reader = new DerSequenceReader(extension.RawData);

            while (reader.HasData)
            {
                // Policy Constraints context specific tag values are defined in RFC 3280 4.2.1.12,
                // and restated (unchanged) in RFC 5280 4.2.1.11.
                switch (reader.PeekTag())
                {
                    case DerSequenceReader.ContextSpecificTagFlag | 0:
                        policy.RequireExplicitPolicyDepth = reader.ReadInteger();
                        break;
                    case DerSequenceReader.ContextSpecificTagFlag | 1:
                        policy.InhibitMappingDepth = reader.ReadInteger();
                        break;
                    default:
                        if (extension.Critical)
                        {
                            // If an unknown value is read, but we're marked as critical,
                            // then we don't know what we're doing and MUST fail validation
                            // (RFC 3280).
                            // If it isn't critical then it means we're allowed to be ignorant
                            // of data defined more recently than we understand.
                            throw new CryptographicException();
                        }

                        break;
                }
            }
        }
Ejemplo n.º 23
0
        internal static ISet<string> ReadCertPolicyExtension(X509Extension extension)
        {
            DerSequenceReader reader = new DerSequenceReader(extension.RawData);
            HashSet<string> policies = new HashSet<string>();

            while (reader.HasData)
            {
                DerSequenceReader policyInformation = reader.ReadSequence();
                policies.Add(policyInformation.ReadOidAsString());

                // There is an optional policy qualifier here, but it is for information
                // purposes, there is no logic that would be changed.

                // Since reader (the outer one) has already skipped past the rest of the
                // sequence we don't particularly need to drain out here.
            }

            return policies;
        }
		// methods

		public int Add (X509Extension extension) 
		{
			return _list.Add (extension);
		}
Ejemplo n.º 25
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
		}
Ejemplo n.º 26
0
		public void ConstructorAsnEncodedData_WithNullOid ()
		{
			AsnEncodedData aed = new AsnEncodedData (new byte[] { 0x30, 0x05, 0x06, 0x03, 0x2A, 0x03, 0x04 });
			X509Extension eku = new X509Extension (aed, true);
		}
		public void WrongExtension_X509Extension_KeyUsages ()
		{
			X509Extension ex = new X509Extension ("1.2.3", new byte[0], true);
			X509KeyUsageExtension ku = new X509KeyUsageExtension ();
			ku.CopyFrom (ex);
			Assert.AreEqual (0, ku.KeyUsages, "KeyUsages");
		}
Ejemplo n.º 28
0
 internal X509AuthorityKeyIdentifierExtension(X509Extension untypedAkid)
     : base(untypedAkid, untypedAkid.Critical)
 {
     _decoded = false;
 }
 public int Add(X509Extension extension)
 {
     return(default(int));
 }
Ejemplo n.º 30
0
        private static unsafe CertificateRequest LoadSigningRequest(
            ReadOnlySpan <byte> pkcs10,
            bool permitTrailingData,
            HashAlgorithmName signerHashAlgorithm,
            out int bytesConsumed,
            CertificateRequestLoadOptions options,
            RSASignaturePadding?signerSignaturePadding)
        {
            ArgumentException.ThrowIfNullOrEmpty(signerHashAlgorithm.Name, nameof(signerHashAlgorithm));

            if ((options & ~AllOptions) != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options), options, SR.Argument_InvalidFlag);
            }

            bool skipSignatureValidation =
                (options & CertificateRequestLoadOptions.SkipSignatureValidation) != 0;

            bool unsafeLoadCertificateExtensions =
                (options & CertificateRequestLoadOptions.UnsafeLoadCertificateExtensions) != 0;

            try
            {
                AsnValueReader outer         = new AsnValueReader(pkcs10, AsnEncodingRules.DER);
                int            encodedLength = outer.PeekEncodedValue().Length;

                AsnValueReader     pkcs10Asn = outer.ReadSequence();
                CertificateRequest req;

                if (!permitTrailingData)
                {
                    outer.ThrowIfNotEmpty();
                }

                fixed(byte *p10ptr = pkcs10)
                {
                    using (PointerMemoryManager <byte> manager = new PointerMemoryManager <byte>(p10ptr, encodedLength))
                    {
                        ReadOnlyMemory <byte>       rebind             = manager.Memory;
                        ReadOnlySpan <byte>         encodedRequestInfo = pkcs10Asn.PeekEncodedValue();
                        CertificationRequestInfoAsn requestInfo;
                        AlgorithmIdentifierAsn      algorithmIdentifier;
                        ReadOnlySpan <byte>         signature;
                        int signatureUnusedBitCount;

                        CertificationRequestInfoAsn.Decode(ref pkcs10Asn, rebind, out requestInfo);
                        AlgorithmIdentifierAsn.Decode(ref pkcs10Asn, rebind, out algorithmIdentifier);

                        if (!pkcs10Asn.TryReadPrimitiveBitString(out signatureUnusedBitCount, out signature))
                        {
                            throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                        }

                        pkcs10Asn.ThrowIfNotEmpty();

                        if (requestInfo.Version < 0)
                        {
                            throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                        }

                        // They haven't bumped from v0 to v1 as of 2022.
                        const int MaxSupportedVersion = 0;

                        if (requestInfo.Version != MaxSupportedVersion)
                        {
                            throw new CryptographicException(
                                      SR.Format(
                                          SR.Cryptography_CertReq_Load_VersionTooNew,
                                          requestInfo.Version,
                                          MaxSupportedVersion));
                        }

                        PublicKey publicKey = PublicKey.DecodeSubjectPublicKeyInfo(ref requestInfo.SubjectPublicKeyInfo);

                        if (!skipSignatureValidation)
                        {
                            // None of the supported signature algorithms support signatures that are not full bytes.
                            // So, shortcut the verification on the bit length
                            if (signatureUnusedBitCount != 0 ||
                                !VerifyX509Signature(encodedRequestInfo, signature, publicKey, algorithmIdentifier))
                            {
                                throw new CryptographicException(SR.Cryptography_CertReq_SignatureVerificationFailed);
                            }
                        }

                        X500DistinguishedName subject = new X500DistinguishedName(requestInfo.Subject.Span);

                        req = new CertificateRequest(
                            subject,
                            publicKey,
                            signerHashAlgorithm,
                            signerSignaturePadding);

                        if (requestInfo.Attributes is not null)
                        {
                            bool foundCertExt = false;

                            foreach (AttributeAsn attr in requestInfo.Attributes)
                            {
                                if (attr.AttrType == Oids.Pkcs9ExtensionRequest)
                                {
                                    if (foundCertExt)
                                    {
                                        throw new CryptographicException(
                                                  SR.Cryptography_CertReq_Load_DuplicateExtensionRequests);
                                    }

                                    foundCertExt = true;

                                    if (attr.AttrValues.Length != 1)
                                    {
                                        throw new CryptographicException(
                                                  SR.Cryptography_CertReq_Load_DuplicateExtensionRequests);
                                    }

                                    AsnValueReader extsReader = new AsnValueReader(
                                        attr.AttrValues[0].Span,
                                        AsnEncodingRules.DER);

                                    AsnValueReader exts = extsReader.ReadSequence();
                                    extsReader.ThrowIfNotEmpty();

                                    // Minimum length is 1, so do..while
                                    do
                                    {
                                        X509ExtensionAsn.Decode(ref exts, rebind, out X509ExtensionAsn extAsn);

                                        if (unsafeLoadCertificateExtensions)
                                        {
                                            X509Extension ext = new X509Extension(
                                                extAsn.ExtnId,
                                                extAsn.ExtnValue.Span,
                                                extAsn.Critical);

                                            X509Extension?rich =
                                                X509Certificate2.CreateCustomExtensionIfAny(extAsn.ExtnId);

                                            if (rich is not null)
                                            {
                                                rich.CopyFrom(ext);
                                                req.CertificateExtensions.Add(rich);
                                            }
                                            else
                                            {
                                                req.CertificateExtensions.Add(ext);
                                            }
                                        }
                                    } while (exts.HasData);
                                }
                                else
                                {
                                    if (attr.AttrValues.Length == 0)
                                    {
                                        throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                                    }

                                    foreach (ReadOnlyMemory <byte> val in attr.AttrValues)
                                    {
                                        req.OtherRequestAttributes.Add(
                                            new AsnEncodedData(attr.AttrType, val.Span));
                                    }
                                }
                            }
                        }
                    }
                }

                bytesConsumed = encodedLength;
                return(req);
            }
            catch (AsnContentException e)
            {
                throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
            }
        }
Ejemplo n.º 31
0
 public int Add(X509Extension extension)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Qualification of extension by type
        /// </summary>
        /// <param name="asn1Encodable"></param>
        /// <returns></returns>
        private System.Security.Cryptography.X509Certificates.X509Extension QualificationExtension(Asn1Encodable asn1Encodable)
        {
            Asn1Sequence s = Asn1Sequence.GetInstance(asn1Encodable.ToAsn1Object());

            if (s.Count < 2 || s.Count > 3)
            {
                throw new ArgumentException("Bad sequence size: " + s.Count);
            }

            DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(s[0].ToAsn1Object());

            bool isCritical = s.Count == 3 &&
                              DerBoolean.GetInstance(s[1].ToAsn1Object()).IsTrue;

            Asn1OctetString octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object());

            var extension = new System.Security.Cryptography.X509Certificates.X509Extension(new Oid(oid.Id), octets.GetOctets(), isCritical);

            var value = Asn1Object.FromByteArray(octets.GetOctets());

            switch (extension.Oid.Value)
            {
            case OidExtensions.SubjectKeyIdentifier:
                var spki = Asn1OctetString.GetInstance(value).GetOctets();
                extension = new X509SubjectKeyIdentifierExtension(spki, isCritical);
                break;

            case OidExtensions.ExtKeyUsage:
                var bcEKU           = ExtendedKeyUsage.GetInstance(value);
                var collectionFlags = new OidCollection();
                foreach (DerObjectIdentifier item in bcEKU.GetAllUsages())
                {
                    collectionFlags.Add(new Oid(item.Id));
                }
                extension = new X509EnhancedKeyUsageExtension(collectionFlags, isCritical);
                break;

            case OidExtensions.KeyUsage:
                var    bitString = DerBitString.GetInstance(value);
                byte[] data      = bitString.GetBytes();
                var    keyUsage  = data.Length == 1
                        ? data[0] & 0xff
                        : (data[1] & 0xff) << 8 | (data[0] & 0xff);
                extension = new X509KeyUsageExtension((X509KeyUsageFlags)keyUsage, isCritical);
                break;

            case OidExtensions.BasicConstraints:
                var bcBC = BasicConstraints.GetInstance(value);
                extension = new X509BasicConstraintsExtension(bcBC.IsCA(), true, bcBC.PathLenConstraint.IntValue, isCritical);
                break;

            case OidExtensions.TemplateV2:
                extension = new X509TemplateExtensionV2(octets.GetOctets(), isCritical);
                break;

            case OidExtensions.TemplateV1:
                extension = new X509TemplateExtensionV1(octets.GetOctets(), isCritical);
                break;

            default:
                break;
            }
            return(extension);
        }
Ejemplo n.º 33
0
 private static int ReadInhibitAnyPolicyExtension(X509Extension extension)
 {
     DerSequenceReader reader = DerSequenceReader.CreateForPayload(extension.RawData);
     return reader.ReadInteger();
 }
        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());
        }
Ejemplo n.º 35
0
        private static ISet<string> ReadExtendedKeyUsageExtension(X509Extension extension)
        {
            X509EnhancedKeyUsageExtension ekusExtension = (X509EnhancedKeyUsageExtension)extension;
            HashSet<string> oids = new HashSet<string>();

            foreach (Oid oid in ekusExtension.EnhancedKeyUsages)
            {
                oids.Add(oid.Value);
            }

            return oids;
        }
		public void WrongExtension_X509Extension ()
		{
			X509Extension ex = new X509Extension ("1.2.3", new byte[0], true);
			OidCollection oc = new OidCollection ();
			oc.Add (new Oid ("1.2.3.4"));
			X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension (oc, false);
			Assert.AreEqual (1, eku.EnhancedKeyUsages.Count, "EnhancedKeyUsages");
			Assert.IsFalse (eku.Critical, "Critical");
			eku.CopyFrom (ex);
			Assert.IsTrue (eku.Critical, "Critical");
			Assert.AreEqual (String.Empty, BitConverter.ToString (eku.RawData), "RawData");
			Assert.AreEqual ("1.2.3", eku.Oid.Value, "Oid.Value");
			Assert.IsNull (eku.Oid.FriendlyName, "Oid.FriendlyName");
		}
Ejemplo n.º 37
0
        private static List<CertificatePolicyMapping> ReadCertPolicyMappingsExtension(X509Extension extension)
        {
            DerSequenceReader reader = new DerSequenceReader(extension.RawData);
            List<CertificatePolicyMapping> mappings = new List<CertificatePolicyMapping>();

            while (reader.HasData)
            {
                DerSequenceReader mappingSequence = reader.ReadSequence();
                mappings.Add(
                    new CertificatePolicyMapping
                    {
                        IssuerDomainPolicy = mappingSequence.ReadOidAsString(),
                        SubjectDomainPolicy = mappingSequence.ReadOidAsString(),
                    });
            }

            return mappings;
        }
		public void WrongExtension_X509Extension_KeyUsages ()
		{
			X509Extension ex = new X509Extension ("1.2.3", new byte[0], true);
			X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension ();
			eku.CopyFrom (ex);
			Assert.AreEqual (0, eku.EnhancedKeyUsages.Count, "EnhancedKeyUsages");
		}
Ejemplo n.º 39
0
        internal unsafe X509ExtensionCollection(SafeCertContextHandle safeCertContextHandle) {
            using (SafeCertContextHandle certContext = CAPI.CertDuplicateCertificateContext(safeCertContextHandle)) {
                CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) certContext.DangerousGetHandle());
                CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO));
                uint cExtensions = pCertInfo.cExtension;
                IntPtr rgExtensions = pCertInfo.rgExtension;

                for (uint index = 0; index < cExtensions; index++) {
                    X509Extension extension = new X509Extension(new IntPtr((long)rgExtensions + (index * Marshal.SizeOf(typeof(CAPI.CERT_EXTENSION)))));
                    X509Extension customExtension = CryptoConfig.CreateFromName(extension.Oid.Value) as X509Extension;
                    if (customExtension != null) {
                        customExtension.CopyFrom(extension);
                        extension = customExtension;
                    }
                    Add(extension);
                }
            }
        }
		public void WrongExtension_X509Extension ()
		{
			X509Extension ex = new X509Extension ("1.2.3", new byte[0], true);
			X509SubjectKeyIdentifierExtension ski = new X509SubjectKeyIdentifierExtension ("www.go-mono.com", false); // odd length
			Assert.IsFalse (ski.Critical, "Critical");
			Assert.AreEqual ("FFFFFFFFFFFFFF", ski.SubjectKeyIdentifier, "SubjectKeyIdentifier");
			Assert.AreEqual ("ff ff ff ff ff ff ff" + Environment.NewLine, ski.Format (true), "Format(true)");
			Assert.AreEqual ("ff ff ff ff ff ff ff", ski.Format (false), "Format(false)");

			ski.CopyFrom (ex);
			Assert.IsTrue (ski.Critical, "Critical");
			Assert.AreEqual (String.Empty, BitConverter.ToString (ski.RawData), "RawData");
			Assert.AreEqual ("1.2.3", ski.Oid.Value, "Oid.Value");
			// FIXME: Don't expect that FriendlyName is English. This test fails under non-English Windows.
			//Assert.IsNull (ski.Oid.FriendlyName, "Oid.FriendlyName");
			Assert.AreEqual (String.Empty, ski.Format (true), "Format(true)");
			Assert.AreEqual (String.Empty, ski.Format (false), "Format(false)");
		}
            // 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;
                }
            }
		public void WrongExtension_X509Extension_CertificateAuthority ()
		{
			X509Extension ex = new X509Extension ("1.2.3", new byte[0], true);
			X509SubjectKeyIdentifierExtension ski = new X509SubjectKeyIdentifierExtension ();
			ski.CopyFrom (ex);
			string s = ski.SubjectKeyIdentifier;
		}
Ejemplo n.º 43
0
 public void CopyTo(X509Extension[] array, int index)
 {
     ((ICollection)this).CopyTo(array, index);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="X509ExtensionWrapper"/> class.
 /// </summary>
 /// <param name="extension">The extension.</param>
 protected X509ExtensionWrapper(X509Extension extension)
 {
     x509ext = extension;
 }