internal X509ExtensionCollection (MX.X509Certificate cert) { _list = new ArrayList (cert.Extensions.Count); if (cert.Extensions.Count == 0) return; object[] parameters = new object [2]; foreach (MX.X509Extension ext in cert.Extensions) { bool critical = ext.Critical; string oid = ext.Oid; byte[] raw_data = null; // extension data is embedded in an octet stream (4) ASN1 value = ext.Value; if ((value.Tag == 0x04) && (value.Count > 0)) raw_data = value [0].GetBytes (); parameters [0] = new AsnEncodedData (oid, raw_data); parameters [1] = critical; X509Extension newt = (X509Extension) CryptoConfig.CreateFromName (oid, parameters); if (newt == null) { // not registred in CryptoConfig, using default newt = new X509Extension (oid, raw_data, critical); } _list.Add (newt); } }
public int Add (X509Extension extension) { if (extension == null) throw new ArgumentNullException ("extension"); if (readOnly) throw new NotSupportedException ("Extensions are read only"); return InnerList.Add (extension); }
public void AddRange (X509Extension[] extension) { if (extension == null) throw new ArgumentNullException ("extension"); if (readOnly) throw new NotSupportedException ("Extensions are read only"); for (int i = 0; i < extension.Length; i++) InnerList.Add (extension [i]); }
public X509ExtensionCollection (ASN1 asn1) : this () { readOnly = true; if (asn1 == null) return; if (asn1.Tag != 0x30) throw new Exception ("Invalid extensions format"); for (int i=0; i < asn1.Count; i++) { X509Extension extension = new X509Extension (asn1 [i]); InnerList.Add (extension); } }
/// <summary> /// Create an extension from an existing X509 extension /// </summary> /// <remarks>Sub classses must provide an implementation to decode their values</remarks> /// <param name="Extension">X509 extension</param> public ProfileExtension(X509Extension Extension) { critical = Extension.IsCritical; }
/** * Returns a string representation of this CRL. * * @return a string representation of this CRL. */ public override string ToString() { StringBuilder buf = new StringBuilder(); string nl = Platform.NewLine; buf.Append(" Version: ").Append(this.Version).Append(nl); buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl); buf.Append(" This update: ").Append(this.ThisUpdate).Append(nl); buf.Append(" Next update: ").Append(this.NextUpdate).Append(nl); buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl); byte[] sig = this.GetSignature(); buf.Append(" Signature: "); buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl); for (int i = 20; i < sig.Length; i += 20) { int count = System.Math.Min(20, sig.Length - i); buf.Append(" "); buf.Append(Hex.ToHexString(sig, i, count)).Append(nl); } X509Extensions extensions = c.TbsCertList.Extensions; if (extensions != null) { IEnumerator e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { buf.Append(" Extensions: ").Append(nl); } do { DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) { Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value); buf.Append(" critical(").Append(ext.IsCritical).Append(") "); try { if (oid.Equals(X509Extensions.CrlNumber)) { buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl); } else if (oid.Equals(X509Extensions.DeltaCrlIndicator)) { buf.Append( "Base CRL: " + new CrlNumber(DerInteger.GetInstance( asn1Value).PositiveValue)) .Append(nl); } else if (oid.Equals(X509Extensions.IssuingDistributionPoint)) { buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl); } else if (oid.Equals(X509Extensions.CrlDistributionPoints)) { buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl); } else if (oid.Equals(X509Extensions.FreshestCrl)) { buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl); } else { buf.Append(oid.Id); buf.Append(" value = ").Append( Asn1Dump.DumpAsString(asn1Value)) .Append(nl); } } catch (Exception) { buf.Append(oid.Id); buf.Append(" value = ").Append("*****").Append(nl); } } else { buf.Append(nl); } }while (e.MoveNext()); } ISet certSet = GetRevokedCertificates(); if (certSet != null) { foreach (X509CrlEntry entry in certSet) { buf.Append(entry); buf.Append(nl); } } return(buf.ToString()); }
public void CheckCertificate( int id, byte[] cert) { Asn1Object seq = Asn1Object.FromByteArray(cert); string dump = Asn1Dump.DumpAsString(seq); X509CertificateStructure obj = X509CertificateStructure.GetInstance(seq); TbsCertificateStructure tbsCert = obj.TbsCertificate; if (!tbsCert.Subject.ToString().Equals(subjects[id - 1])) { Fail("failed subject test for certificate id " + id + " got " + tbsCert.Subject.ToString()); } if (tbsCert.Version == 3) { X509Extensions ext = tbsCert.Extensions; if (ext != null) { foreach (DerObjectIdentifier oid in ext.ExtensionOids) { X509Extension extVal = ext.GetExtension(oid); Asn1Object extObj = Asn1Object.FromByteArray(extVal.Value.GetOctets()); if (oid.Equals(X509Extensions.SubjectKeyIdentifier)) { SubjectKeyIdentifier.GetInstance(extObj); } else if (oid.Equals(X509Extensions.KeyUsage)) { KeyUsage.GetInstance(extObj); } else if (oid.Equals(X509Extensions.ExtendedKeyUsage)) { ExtendedKeyUsage ku = ExtendedKeyUsage.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)ku.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { KeyPurposeID.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.SubjectAlternativeName)) { GeneralNames gn = GeneralNames.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { GeneralName.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.IssuerAlternativeName)) { GeneralNames gn = GeneralNames.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { GeneralName.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.CrlDistributionPoints)) { CrlDistPoint p = CrlDistPoint.GetInstance(extObj); DistributionPoint[] points = p.GetDistributionPoints(); for (int i = 0; i != points.Length; i++) { // do nothing } } else if (oid.Equals(X509Extensions.CertificatePolicies)) { Asn1Sequence cp = (Asn1Sequence)extObj; for (int i = 0; i != cp.Count; i++) { PolicyInformation.GetInstance(cp[i]); } } else if (oid.Equals(X509Extensions.AuthorityKeyIdentifier)) { AuthorityKeyIdentifier.GetInstance(extObj); } else if (oid.Equals(X509Extensions.BasicConstraints)) { BasicConstraints.GetInstance(extObj); } else { //Console.WriteLine(oid.Id); } } } } }
public BasicConstraintsExtension(X509Extension extension) : base(extension) { }
public static void ReproduceBigExponentCert() { DateTimeOffset notBefore = new DateTimeOffset(2016, 3, 2, 1, 48, 0, TimeSpan.Zero); DateTimeOffset notAfter = new DateTimeOffset(2017, 3, 2, 1, 48, 0, TimeSpan.Zero); byte[] serialNumber = "9B5DE6C15126A58B".HexToByteArray(); var subject = new X500DistinguishedName( "CN=localhost, OU=.NET Framework (CoreFX), O=Microsoft Corporation, L=Redmond, S=Washington, C=US"); X509Extension skidExtension = new X509SubjectKeyIdentifierExtension( "78A5C75D51667331D5A96924114C9B5FA00D7BCB", false); X509Extension akidExtension = new X509Extension( "2.5.29.35", "3016801478A5C75D51667331D5A96924114C9B5FA00D7BCB".HexToByteArray(), false); X509Extension basicConstraints = new X509BasicConstraintsExtension(true, false, 0, false); X509Certificate2 cert; using (RSA rsa = RSA.Create()) { rsa.ImportParameters(TestData.RsaBigExponentParams); var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(skidExtension); request.CertificateExtensions.Add(akidExtension); request.CertificateExtensions.Add(basicConstraints); var signatureGenerator = X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1); cert = request.Create(subject, signatureGenerator, notBefore, notAfter, serialNumber); } const string expectedHex = "308203EB308202D3A0030201020209009B5DE6C15126A58B300D06092A864886" + "F70D01010B050030818A310B3009060355040613025553311330110603550408" + "130A57617368696E67746F6E3110300E060355040713075265646D6F6E64311E" + "301C060355040A13154D6963726F736F667420436F72706F726174696F6E3120" + "301E060355040B13172E4E4554204672616D65776F726B2028436F7265465829" + "31123010060355040313096C6F63616C686F7374301E170D3136303330323031" + "343830305A170D3137303330323031343830305A30818A310B30090603550406" + "13025553311330110603550408130A57617368696E67746F6E3110300E060355" + "040713075265646D6F6E64311E301C060355040A13154D6963726F736F667420" + "436F72706F726174696F6E3120301E060355040B13172E4E4554204672616D65" + "776F726B2028436F726546582931123010060355040313096C6F63616C686F73" + "7430820124300D06092A864886F70D010101050003820111003082010C028201" + "0100AF81C1CBD8203F624A539ED6608175372393A2837D4890E48A19DED36973" + "115620968D6BE0D3DAA38AA777BE02EE0B6B93B724E8DCC12B632B4FA80BBC92" + "5BCE624F4CA7CC606306B39403E28C932D24DD546FFE4EF6A37F10770B2215EA" + "8CBB5BF427E8C4D89B79EB338375100C5F83E55DE9B4466DDFBEEE42539AEF33" + "EF187B7760C3B1A1B2103C2D8144564A0C1039A09C85CF6B5974EB516FC8D662" + "3C94AE3A5A0BB3B4C792957D432391566CF3E2A52AFB0C142B9E0681B8972671" + "AF2B82DD390A39B939CF719568687E4990A63050CA7768DCD6B378842F18FDB1" + "F6D9FF096BAF7BEB98DCF930D66FCFD503F58D41BFF46212E24E3AFC45EA42BD" + "884702050200000441A350304E301D0603551D0E0416041478A5C75D51667331" + "D5A96924114C9B5FA00D7BCB301F0603551D2304183016801478A5C75D516673" + "31D5A96924114C9B5FA00D7BCB300C0603551D13040530030101FF300D06092A" + "864886F70D01010B0500038201010077756D05FFA6ADFED5B6D4AFB540840C6D" + "01CF6B3FA6C973DFD61FCAA0A814FA1E2469019D94B1D856D07DD2B95B8550DF" + "D2085953A494B99EFCBAA7982CE771984F9D4A445FFEE062E8A049736A39FD99" + "4E1FDA0A5DC2B5B0E57A0B10C41BC7FE6A40B24F85977302593E60B98DD4811D" + "47D948EDF8D6E6B5AF80A1827496E20BFD240E467674504D4E4703331D64705C" + "36FB6E14BABFD9CBEEC44B33A8D7B36479900F3C5BBAB69C5E453D180783E250" + "8051B998C038E4622571D2AB891D898E5458828CF18679517D28DBCABF72E813" + "07BFD721B73DDB1751123F99D8FC0D533798C4DBD14719D5D8A85B00A144A367" + "677B48891A9B56F045334811BACB7A"; using (cert) { Assert.Equal(expectedHex, cert.RawData.ByteArrayToHex()); } }
public void ConstructorAsnEncodedData_Null() { X509Extension ex = new X509Extension((AsnEncodedData)null, true); }
public void CopyTo (X509Extension[] array, int index) { if (array == null) throw new ArgumentNullException ("array"); if (index < 0) throw new ArgumentOutOfRangeException ("negative index"); if (index >= array.Length) throw new ArgumentOutOfRangeException ("index >= array.Length"); _list.CopyTo (array, index); }
public AuthorityKeyIdentifierExtension(X509Extension extension) : base(extension) { }
public void Insert (int index, X509Extension extension) { if (extension == null) throw new ArgumentNullException ("extension"); InnerList.Insert (index, extension); }
public void Remove (X509Extension extension) { if (extension == null) throw new ArgumentNullException ("extension"); InnerList.Remove (extension); }
public int IndexOf (X509Extension extension) { if (extension == null) throw new ArgumentNullException ("extension"); for (int i=0; i < InnerList.Count; i++) { X509Extension ex = (X509Extension) InnerList [i]; if (ex.Equals (extension)) return i; } return -1; }
public void CopyTo (X509Extension[] extensions, int index) { if (extensions == null) throw new ArgumentNullException ("extensions"); InnerList.CopyTo (extensions, index); }
public NetscapeCertTypeExtension(X509Extension extension) : base(extension) { }
public static void ReadExtensions() { using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection exts = c.Extensions; int count = exts.Count; Assert.Equal(6, count); X509Extension[] extensions = new X509Extension[count]; exts.CopyTo(extensions, 0); extensions = extensions.OrderBy(e => e.Oid.Value).ToArray(); // There are an awful lot of magic-looking values in this large test. // These values are embedded within the certificate, and the test is // just verifying the object interpretation. In the event the test data // (TestData.MsCertificate) is replaced, this whole body will need to be // redone. { // Authority Information Access X509Extension aia = extensions[0]; Assert.Equal("1.3.6.1.5.5.7.1.1", aia.Oid.Value); Assert.False(aia.Critical); byte[] expectedDer = ( "304c304a06082b06010505073002863e687474703a2f2f7777772e6d" + "6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f" + "645369675043415f30382d33312d323031302e637274").HexToByteArray(); Assert.Equal(expectedDer, aia.RawData); } { // Subject Key Identifier X509Extension skid = extensions[1]; Assert.Equal("2.5.29.14", skid.Oid.Value); Assert.False(skid.Critical); byte[] expected = "04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(); Assert.Equal(expected, skid.RawData); Assert.True(skid is X509SubjectKeyIdentifierExtension); X509SubjectKeyIdentifierExtension rich = (X509SubjectKeyIdentifierExtension)skid; Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", rich.SubjectKeyIdentifier); } { // Subject Alternative Names X509Extension sans = extensions[2]; Assert.Equal("2.5.29.17", sans.Oid.Value); Assert.False(sans.Critical); byte[] expected = ( "3048a4463044310d300b060355040b13044d4f505231333031060355" + "0405132a33313539352b34666166306237312d616433372d34616133" + "2d613637312d373662633035323334346164").HexToByteArray(); Assert.Equal(expected, sans.RawData); } { // CRL Distribution Points X509Extension cdps = extensions[3]; Assert.Equal("2.5.29.31", cdps.Oid.Value); Assert.False(cdps.Critical); byte[] expected = ( "304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f" + "66742e636f6d2f706b692f63726c2f70726f64756374732f4d696343" + "6f645369675043415f30382d33312d323031302e63726c").HexToByteArray(); Assert.Equal(expected, cdps.RawData); } { // Authority Key Identifier X509Extension akid = extensions[4]; Assert.Equal("2.5.29.35", akid.Oid.Value); Assert.False(akid.Critical); byte[] expected = "30168014cb11e8cad2b4165801c9372e331616b94c9a0a1f".HexToByteArray(); Assert.Equal(expected, akid.RawData); } { // Extended Key Usage (X.509/2000 says Extended, Win32/NetFX say Enhanced) X509Extension eku = extensions[5]; Assert.Equal("2.5.29.37", eku.Oid.Value); Assert.False(eku.Critical); byte[] expected = "300a06082b06010505070303".HexToByteArray(); Assert.Equal(expected, eku.RawData); Assert.True(eku is X509EnhancedKeyUsageExtension); X509EnhancedKeyUsageExtension rich = (X509EnhancedKeyUsageExtension)eku; OidCollection usages = rich.EnhancedKeyUsages; Assert.Equal(1, usages.Count); Oid oid = usages[0]; // Code Signing Assert.Equal("1.3.6.1.5.5.7.3.3", oid.Value); } } }
public void ConstructorOid_RawNull() { X509Extension ex = new X509Extension(new Oid("1.2.3"), null, true); }
public void CopyTo(X509Extension[] array, int index);
public void ConstructorString_RawNull() { X509Extension ex = new X509Extension("1.2.3", null, true); }
/// <summary> /// Add a extension to the certificate in addition to the default extensions. /// </summary> /// <remarks> /// By default the following X509 extensions are added to a certificate, /// some depending on certificate type: /// CA/SubCA/OPC UA application: /// X509BasicConstraintsExtension /// X509SubjectKeyIdentifierExtension /// X509AuthorityKeyIdentifierExtension /// X509KeyUsageExtension /// OPC UA application: /// X509SubjectAltNameExtension /// X509EnhancedKeyUsageExtension /// </remarks> /// <param name="extension"></param> /// <returns></returns> public virtual ICertificateBuilder AddExtension(X509Extension extension) { m_extensions.Add(extension); return(this); }
public override string ToString() { StringBuilder buf = new StringBuilder(); string nl = Platform.NewLine; buf.Append(" userCertificate: ").Append(this.SerialNumber).Append(nl); buf.Append(" revocationDate: ").Append(this.RevocationDate).Append(nl); buf.Append(" certificateIssuer: ").Append(this.GetCertificateIssuer()).Append(nl); X509Extensions extensions = c.Extensions; if (extensions != null) { IEnumerator e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { buf.Append(" crlEntryExtensions:").Append(nl); do { DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) { Asn1Object obj = Asn1Object.FromByteArray(ext.Value.GetOctets()); buf.Append(" critical(") .Append(ext.IsCritical) .Append(") "); try { if (oid.Equals(X509Extensions.ReasonCode)) { buf.Append(new CrlReason(DerEnumerated.GetInstance(obj))); } else if (oid.Equals(X509Extensions.CertificateIssuer)) { buf.Append("Certificate issuer: ").Append( GeneralNames.GetInstance((Asn1Sequence)obj)); } else { buf.Append(oid.Id); buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj)); } buf.Append(nl); } catch (Exception) { buf.Append(oid.Id); buf.Append(" value = ").Append("*****").Append(nl); } } else { buf.Append(nl); } }while (e.MoveNext()); } } return(buf.ToString()); }
public void ConstructorOid_Null() { X509Extension ex = new X509Extension((Oid)null, new byte[] { 0x30, 0x01 }, true); }
/// <summary> /// Create the X509 extensions to build the certificate. /// </summary> /// <param name="request"></param> private void CreateX509Extensions(CertificateRequest request) { // Basic Constraints X509BasicConstraintsExtension bc = GetBasicContraints(); request.CertificateExtensions.Add(bc); // Subject Key Identifier var ski = new X509SubjectKeyIdentifierExtension( request.PublicKey, X509SubjectKeyIdentifierHashAlgorithm.Sha1, false); request.CertificateExtensions.Add(ski); // Authority Key Identifier X509Extension authorityKeyIdentifier = IssuerCAKeyCert != null ? X509Extensions.BuildAuthorityKeyIdentifier(IssuerCAKeyCert) : new X509AuthorityKeyIdentifierExtension( ski.SubjectKeyIdentifier.FromHexString(), SubjectName, m_serialNumber ); request.CertificateExtensions.Add(authorityKeyIdentifier); X509KeyUsageFlags keyUsageFlags; if (m_isCA) { keyUsageFlags = X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign; } else { // Key Usage keyUsageFlags = X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.KeyEncipherment; if (IssuerCAKeyCert == null) { // self signed case keyUsageFlags |= X509KeyUsageFlags.KeyCertSign; } } request.CertificateExtensions.Add( new X509KeyUsageExtension( keyUsageFlags, true)); if (!m_isCA) { // Enhanced key usage request.CertificateExtensions.Add( new X509EnhancedKeyUsageExtension( new OidCollection { new Oid(Oids.ServerAuthentication), new Oid(Oids.ClientAuthentication) }, true)); } foreach (var extension in m_extensions) { request.CertificateExtensions.Add(extension); } }
public void ConstructorString_Null() { X509Extension ex = new X509Extension((string)null, new byte[] { 0x30, 0x01 }, true); }
public bool Contains (X509Extension extension) { return (IndexOf (extension) != -1); }
public void ConstructorAsnEncodedData_WithNullOid() { AsnEncodedData aed = new AsnEncodedData(new byte[] { 0x30, 0x05, 0x06, 0x03, 0x2A, 0x03, 0x04 }); X509Extension eku = new X509Extension(aed, true); }
/// <summary> /// Initializes a new instance of the <see cref="X509ExtensionWrapper"/> class. /// </summary> /// <param name="extension">The extension.</param> protected X509ExtensionWrapper(X509Extension extension) { x509ext = extension; }
public SubjectAltNameExtension(X509Extension extension) : base(extension) { }
/// <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 KeyUsageExtension(X509Extension extension) : base(extension) { }
public static void ReadExtensions() { using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection exts = c.Extensions; int count = exts.Count; Assert.Equal(6, count); X509Extension[] extensions = new X509Extension[count]; exts.CopyTo(extensions, 0); extensions = extensions.OrderBy(e => e.Oid.Value).ToArray(); // There are an awful lot of magic-looking values in this large test. // These values are embedded within the certificate, and the test is // just verifying the object interpretation. In the event the test data // (TestData.MsCertificate) is replaced, this whole body will need to be // redone. { // Authority Information Access X509Extension aia = extensions[0]; Assert.Equal("1.3.6.1.5.5.7.1.1", aia.Oid.Value); Assert.False(aia.Critical); byte[] expectedDer = ( "304c304a06082b06010505073002863e687474703a2f2f7777772e6d" + "6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f" + "645369675043415f30382d33312d323031302e637274").HexToByteArray(); Assert.Equal(expectedDer, aia.RawData); } { // Subject Key Identifier X509Extension skid = extensions[1]; Assert.Equal("2.5.29.14", skid.Oid.Value); Assert.False(skid.Critical); byte[] expected = "04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(); Assert.Equal(expected, skid.RawData); Assert.True(skid is X509SubjectKeyIdentifierExtension); X509SubjectKeyIdentifierExtension rich = (X509SubjectKeyIdentifierExtension)skid; Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", rich.SubjectKeyIdentifier); } { // Subject Alternative Names X509Extension sans = extensions[2]; Assert.Equal("2.5.29.17", sans.Oid.Value); Assert.False(sans.Critical); byte[] expected = ( "3048a4463044310d300b060355040b13044d4f505231333031060355" + "0405132a33313539352b34666166306237312d616433372d34616133" + "2d613637312d373662633035323334346164").HexToByteArray(); Assert.Equal(expected, sans.RawData); } { // CRL Distribution Points X509Extension cdps = extensions[3]; Assert.Equal("2.5.29.31", cdps.Oid.Value); Assert.False(cdps.Critical); byte[] expected = ( "304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f" + "66742e636f6d2f706b692f63726c2f70726f64756374732f4d696343" + "6f645369675043415f30382d33312d323031302e63726c").HexToByteArray(); Assert.Equal(expected, cdps.RawData); } { // Authority Key Identifier X509Extension akid = extensions[4]; Assert.Equal("2.5.29.35", akid.Oid.Value); Assert.False(akid.Critical); byte[] expected = "30168014cb11e8cad2b4165801c9372e331616b94c9a0a1f".HexToByteArray(); Assert.Equal(expected, akid.RawData); } { // Extended Key Usage (X.509/2000 says Extended, Win32/NetFX say Enhanced) X509Extension eku = extensions[5]; Assert.Equal("2.5.29.37", eku.Oid.Value); Assert.False(eku.Critical); byte[] expected = "300a06082b06010505070303".HexToByteArray(); Assert.Equal(expected, eku.RawData); Assert.True(eku is X509EnhancedKeyUsageExtension); X509EnhancedKeyUsageExtension rich = (X509EnhancedKeyUsageExtension)eku; OidCollection usages = rich.EnhancedKeyUsages; Assert.Equal(1, usages.Count); Oid oid = usages[0]; // Code Signing Assert.Equal("1.3.6.1.5.5.7.3.3", oid.Value); } } }
public void CheckAttributeCertificate( int id, byte[] cert) { Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(cert); string dump = Asn1Dump.DumpAsString(seq); AttributeCertificate obj = AttributeCertificate.GetInstance(seq); AttributeCertificateInfo acInfo = obj.ACInfo; // Version if (!(acInfo.Version.Equals(new DerInteger(1))) && (!(acInfo.Version.Equals(new DerInteger(2))))) { Fail("failed AC Version test for id " + id); } // Holder Holder h = acInfo.Holder; if (h == null) { Fail("failed AC Holder test, it's null, for id " + id); } // Issuer AttCertIssuer aci = acInfo.Issuer; if (aci == null) { Fail("failed AC Issuer test, it's null, for id " + id); } // Signature AlgorithmIdentifier sig = acInfo.Signature; if (sig == null) { Fail("failed AC Signature test for id " + id); } // Serial DerInteger serial = acInfo.SerialNumber; // Validity AttCertValidityPeriod validity = acInfo.AttrCertValidityPeriod; if (validity == null) { Fail("failed AC AttCertValidityPeriod test for id " + id); } // Attributes Asn1Sequence attribSeq = acInfo.Attributes; AttributeX509[] att = new AttributeX509[attribSeq.Count]; for (int i = 0; i < attribSeq.Count; i++) { att[i] = AttributeX509.GetInstance(attribSeq[i]); } // IssuerUniqueId // TODO, how to best test? // X509 Extensions X509Extensions ext = acInfo.Extensions; if (ext != null) { foreach (DerObjectIdentifier oid in ext.ExtensionOids) { X509Extension extVal = ext.GetExtension(oid); } } }
public PrivateKeyUsagePeriodExtension(X509Extension extension) : base(extension) { }
public KeyAttributesExtension(X509Extension extension) : base(extension) { }
public override string ToString() { StringBuilder builder = new StringBuilder(); string newLine = Platform.NewLine; builder.Append(" [0] Version: ").Append(this.Version).Append(newLine); builder.Append(" SerialNumber: ").Append(this.SerialNumber).Append(newLine); builder.Append(" IssuerDN: ").Append(this.IssuerDN).Append(newLine); builder.Append(" Start Date: ").Append(this.NotBefore).Append(newLine); builder.Append(" Final Date: ").Append(this.NotAfter).Append(newLine); builder.Append(" SubjectDN: ").Append(this.SubjectDN).Append(newLine); builder.Append(" Public Key: ").Append(this.GetPublicKey()).Append(newLine); builder.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(newLine); byte[] signature = this.GetSignature(); builder.Append(" Signature: ").Append(Hex.ToHexString(signature, 0, 20)).Append(newLine); for (int i = 20; i < signature.Length; i += 20) { int length = Math.Min(20, signature.Length - i); builder.Append(" ").Append(Hex.ToHexString(signature, i, length)).Append(newLine); } X509Extensions extensions = this.c.TbsCertificate.Extensions; if (extensions != null) { IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator(); if (enumerator.MoveNext()) { builder.Append(" Extensions: \n"); } do { DerObjectIdentifier current = (DerObjectIdentifier)enumerator.Current; X509Extension extension = extensions.GetExtension(current); if (extension.Value != null) { Asn1Object obj2 = Asn1Object.FromByteArray(extension.Value.GetOctets()); builder.Append(" critical(").Append(extension.IsCritical).Append(") "); try { if (current.Equals(X509Extensions.BasicConstraints)) { builder.Append(BasicConstraints.GetInstance(obj2)); } else if (current.Equals(X509Extensions.KeyUsage)) { builder.Append(KeyUsage.GetInstance(obj2)); } else if (current.Equals(MiscObjectIdentifiers.NetscapeCertType)) { builder.Append(new NetscapeCertType((DerBitString)obj2)); } else if (current.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl)) { builder.Append(new NetscapeRevocationUrl((DerIA5String)obj2)); } else if (current.Equals(MiscObjectIdentifiers.VerisignCzagExtension)) { builder.Append(new VerisignCzagExtension((DerIA5String)obj2)); } else { builder.Append(current.Id); builder.Append(" value = ").Append(Asn1Dump.DumpAsString((Asn1Encodable)obj2)); } } catch (Exception) { builder.Append(current.Id); builder.Append(" value = ").Append("*****"); } } builder.Append(newLine); }while (enumerator.MoveNext()); } return(builder.ToString()); }
private static void RunTest( string targetName, string subjectCN, IList <string> sanDnsNames, bool flattenCase, bool expectedResult) { using (RSA rsa = RSA.Create(TestData.RsaBigExponentParams)) { CertificateRequest request = new CertificateRequest( $"CN={FixCase(subjectCN, flattenCase)}, O=.NET Framework (CoreFX)", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add( new X509KeyUsageExtension( X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.DigitalSignature, false)); if (sanDnsNames != null) { var builder = new SubjectAlternativeNameBuilder(); foreach (string sanDnsName in sanDnsNames) { builder.AddDnsName(sanDnsName); } X509Extension extension = builder.Build(); // The SAN builder will have done DNS case normalization via IdnMapping. // We need to undo that here. if (!flattenCase) { UTF8Encoding encoding = new UTF8Encoding(); byte[] extensionBytes = extension.RawData; Span <byte> extensionSpan = extensionBytes; foreach (string sanDnsName in sanDnsNames) { // If the string is longer than 127 then the quick DER encoding check // is not correct. Assert.InRange(sanDnsName.Length, 1, 127); byte[] lowerBytes = encoding.GetBytes(sanDnsName.ToLowerInvariant()); byte[] mixedBytes = encoding.GetBytes(sanDnsName); // Only 7-bit ASCII should be here, no byte expansion. // (non-7-bit ASCII values require IdnMapping normalization) Assert.Equal(sanDnsName.Length, lowerBytes.Length); Assert.Equal(sanDnsName.Length, mixedBytes.Length); int idx = extensionSpan.IndexOf(lowerBytes); while (idx >= 0) { if (idx < 2 || extensionBytes[idx - 2] != 0x82 || extensionBytes[idx - 1] != sanDnsName.Length) { int relativeIdx = extensionSpan.Slice(idx + 1).IndexOf(lowerBytes); idx = idx + 1 + relativeIdx; continue; } mixedBytes.AsSpan().CopyTo(extensionSpan.Slice(idx)); break; } } extension.RawData = extensionBytes; } request.CertificateExtensions.Add(extension); } DateTimeOffset start = DateTimeOffset.UtcNow.AddYears(-1); DateTimeOffset end = start.AddYears(1); using (X509Certificate2 cert = request.CreateSelfSigned(start, end)) { bool isMatch = CheckHostname(cert, targetName); string lowerTarget = targetName.ToLowerInvariant(); bool isLowerMatch = CheckHostname(cert, lowerTarget); if (expectedResult) { Assert.True(isMatch, $"{targetName} matches"); Assert.True(isLowerMatch, $"{lowerTarget} (lowercase) matches"); } else { Assert.False(isMatch, $"{targetName} matches"); Assert.False(isLowerMatch, $"{lowerTarget} (lowercase) matches"); } } } }
// public void setBagAttribute( // DERObjectIdentifier oid, // DEREncodable attribute) // { // pkcs12Attributes.put(oid, attribute); // pkcs12Ordering.addElement(oid); // } // // public DEREncodable getBagAttribute( // DERObjectIdentifier oid) // { // return (DEREncodable)pkcs12Attributes.get(oid); // } // // public Enumeration getBagAttributeKeys() // { // return pkcs12Ordering.elements(); // } public override string ToString() { StringBuilder buf = new StringBuilder(); string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; buf.Append(" [0] Version: ").Append(this.Version).Append(nl); buf.Append(" SerialNumber: ").Append(this.SerialNumber).Append(nl); buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl); buf.Append(" Start Date: ").Append(this.NotBefore).Append(nl); buf.Append(" Final Date: ").Append(this.NotAfter).Append(nl); buf.Append(" SubjectDN: ").Append(this.SubjectDN).Append(nl); buf.Append(" Public Key: ").Append(this.GetPublicKey()).Append(nl); buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl); byte[] sig = this.GetSignature(); buf.Append(" Signature: ").Append(Hex.ToHexString(sig, 0, 20)).Append(nl); for (int i = 20; i < sig.Length; i += 20) { int len = System.Math.Min(20, sig.Length - i); buf.Append(" ").Append(Hex.ToHexString(sig, i, len)).Append(nl); } X509Extensions extensions = c.TbsCertificate.Extensions; if (extensions != null) { IEnumerator e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { buf.Append(" Extensions: \n"); } do { DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) { byte[] octs = ext.Value.GetOctets(); Asn1Object obj = Asn1Object.FromByteArray(octs); buf.Append(" critical(").Append(ext.IsCritical).Append(") "); try { if (oid.Equals(X509Extensions.BasicConstraints)) { buf.Append(BasicConstraints.GetInstance(obj)); } else if (oid.Equals(X509Extensions.KeyUsage)) { buf.Append(KeyUsage.GetInstance(obj)); } else if (oid.Equals(MiscObjectIdentifiers.NetscapeCertType)) { buf.Append(new NetscapeCertType((DerBitString)obj)); } else if (oid.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl)) { buf.Append(new NetscapeRevocationUrl((DerIA5String)obj)); } else if (oid.Equals(MiscObjectIdentifiers.VerisignCzagExtension)) { buf.Append(new VerisignCzagExtension((DerIA5String)obj)); } else { buf.Append(oid.Id); buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj)); //buf.Append(" value = ").Append("*****").Append(nl); } } catch (Exception) { buf.Append(oid.Id); //buf.Append(" value = ").Append(new string(Hex.encode(ext.getValue().getOctets()))).Append(nl); buf.Append(" value = ").Append("*****"); } } buf.Append(nl); }while (e.MoveNext()); } return(buf.ToString()); }
public int Add(X509Extension extension);
public SubjectKeyIdentifierExtension(X509Extension extension) : base(extension) { }
// methods public int Add (X509Extension extension) { if (extension == null) throw new ArgumentNullException ("extension"); return _list.Add (extension); }
EsitoVerifica controllaCrlCert(X509Certificate cert, string cachePath, bool force = false) { //usiamo l'ev solo per i dati di revoca EsitoVerifica ev = new EsitoVerifica(); string CN = cert.SubjectDN.GetValues(X509Name.CN).Cast <string>().FirstOrDefault(); string SN = cert.SubjectDN.GetValues(X509Name.SerialNumber).Cast <string>().FirstOrDefault(); X509Extensions ex = X509Extensions.GetInstance(cert.CertificateStructure.TbsCertificate.Extensions); X509Extension e = ex.GetExtension(X509Extensions.CrlDistributionPoints); if (e == null) { string msg = "CRL distribution points NOT PRESENT in certificate structure"; logger.Debug(msg); ev.status = EsitoVerificaStatus.ErroreGenerico; ev.errorCode = "1411";//nonposso scaricare la CRL ev.message = msg; return(ev); } var crldp = CrlDistPoint.GetInstance(e.GetParsedValue()); List <String> certDpUrlLst = GetCrlDistribtionPoints(crldp); ev.status = EsitoVerificaStatus.Valid; ev.SubjectCN = CN; ev.SubjectDN = SN; int downloadsTrials = 0; List <String> errorLst = new List <string>(); foreach (string url in certDpUrlLst) { try { Uri tryUri = new Uri(url); } catch { logger.ErrorFormat("Unable to download/process CRL URL : {0}", url); continue; } try { X509Crl rootCrl = retreiveCrlUrl(url, cachePath, force); downloadsTrials++; if (rootCrl.IsRevoked(cert)) { X509CrlEntry entry = rootCrl.GetRevokedCertificate(cert.CertificateStructure.SerialNumber.Value); ev.dataRevocaCertificato = entry.RevocationDate; logger.DebugFormat("Certificate {0} : {1} with serial {2} is Revoked on {3}", CN, SN, BitConverter.ToString(entry.SerialNumber.ToByteArray()), ev.dataRevocaCertificato); ev.content = entry.SerialNumber.ToByteArray(); ev.errorCode = "1408"; ev.status = EsitoVerificaStatus.Revoked; break; } } catch (Exception exc) { logger.ErrorFormat("Unable to download/process CRL message {0} stack {1} on Download Trial {2}", exc.Message, exc.StackTrace, downloadsTrials); errorLst.Add(exc.Message); } } string ErrorMessage = string.Empty; if ((errorLst.Count > 0) && downloadsTrials == 0) { foreach (string s in errorLst) { ErrorMessage += s + " | "; } } if (!string.IsNullOrEmpty(ErrorMessage)) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.errorCode = "1411";//nonposso scaricare la CRL ev.message = "Unable to download/process CRL message:" + ErrorMessage; } return(ev); }
internal X509ExtensionCollection (MX.X509Certificate cert) { _list = new ArrayList (cert.Extensions.Count); if (cert.Extensions.Count == 0) return; object[] parameters = new object [2]; foreach (MX.X509Extension ext in cert.Extensions) { bool critical = ext.Critical; string oid = ext.Oid; byte[] raw_data = null; // extension data is embedded in an octet stream (4) ASN1 value = ext.Value; if ((value.Tag == 0x04) && (value.Count > 0)) raw_data = value [0].GetBytes (); X509Extension newt = null; #if FULL_AOT_RUNTIME // non-extensible switch (oid) { case "2.5.29.14": newt = new X509SubjectKeyIdentifierExtension (new AsnEncodedData (oid, raw_data), critical); break; case "2.5.29.15": newt = new X509KeyUsageExtension (new AsnEncodedData (oid, raw_data), critical); break; case "2.5.29.19": newt = new X509BasicConstraintsExtension (new AsnEncodedData (oid, raw_data), critical); break; case "2.5.29.37": newt = new X509EnhancedKeyUsageExtension (new AsnEncodedData (oid, raw_data), critical); break; } #else parameters [0] = new AsnEncodedData (oid, raw_data ?? Empty); parameters [1] = critical; newt = (X509Extension) CryptoConfig.CreateFromName (oid, parameters); #endif if (newt == null) { // not registred in CryptoConfig, using default newt = new X509Extension (oid, raw_data ?? Empty, critical); } _list.Add (newt); } }
public CertificatePoliciesExtension(X509Extension extension) : base(extension) { }