void getAttributes(Asn1Reader asn)
 {
     asn.MoveNext();
     if (asn.PayloadLength == 0)
     {
         return;
     }
     do
     {
         X509Attribute attribute = X509Attribute.Decode(asn.GetTagRawData());
         if (attribute.Oid.Value == X509ExtensionOid.CertificateExtensions)
         {
             //Extensions
             var extensions = new X509ExtensionCollection();
             extensions.Decode(attribute.RawData);
             foreach (X509Extension extension in extensions)
             {
                 _extensions.Add(extension);
             }
         }
         else
         {
             _attributes.Add(attribute);
         }
     } while (asn.MoveNextCurrentLevel());
 }
Exemple #2
0
 /// <summary>
 /// Adds unauthenticated attribute. Unlike authenticated attribute, unauthenticated attributes are not protected by signer's signature.
 /// Unauthenticated attributes are replaceable. Such attributes are counter-signing and timestamp. These attributes are informative or
 /// provide their own integrity mechanisms.
 /// </summary>
 /// <param name="attribute">
 /// An attribute that must be protected by digital signature.
 /// </param>
 /// <remarks>
 /// If same attribute (with same object identifier) is already presented in collection, it will be overwritten with attribute in the
 /// <strong>attribute</strong> parameter.
 /// </remarks>
 public void AddUnauthenticatedAttribute(X509Attribute attribute)
 {
     if (attribute == null)
     {
         throw new ArgumentNullException(nameof(attribute));
     }
     addUniqueAttribute(_unauthAttributes, attribute);
 }
Exemple #3
0
 /// <summary>
 /// Converts a default instance of <see cref="X509Attribute"/> class to a specific atrribute implementation object.
 /// </summary>
 /// <param name="attribute">Default instance of <see cref="X509Attribute"/> class.</param>
 /// <returns>Explicit attribute implementation if defined, otherwise, the same object is returned.</returns>
 public static X509Attribute ConvertAttribute(X509Attribute attribute)
 {
     // reserved for future use
     switch (attribute.Oid.Value)
     {
     default:
         return(attribute);
     }
 }
Exemple #4
0
        private IX509AttributeCertificate CreateAttrCert()
        {
//			CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
//			X509Certificate iCert = (X509Certificate) fact
//				.generateCertificate(new ByteArrayInputStream(holderCert));
            X509Certificate iCert = new X509CertificateParser().ReadCertificate(holderCert);

            //
            // a sample key pair.
            //
            // RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
            // new BigInteger(
            // "b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7",
            // 16), new BigInteger("11", 16));

            //
            // set up the keys
            //
//			KeyFactory kFact = KeyFactory.getInstance("RSA", "BC");
//			PrivateKey privKey = kFact.generatePrivate(RsaPrivateKeySpec);
            IAsymmetricKeyParameter privKey = RsaPrivateKeySpec;

            X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator();

            // the actual attributes
            GeneralName         roleName   = new GeneralName(GeneralName.Rfc822Name, "*****@*****.**");
            Asn1EncodableVector roleSyntax = new Asn1EncodableVector(roleName);

            // roleSyntax OID: 2.5.24.72
            X509Attribute attributes = new X509Attribute("2.5.24.72",
                                                         new DerSequence(roleSyntax));

            gen.AddAttribute(attributes);
            gen.SetHolder(new AttributeCertificateHolder(PrincipalUtilities.GetSubjectX509Principal(iCert)));
            gen.SetIssuer(new AttributeCertificateIssuer(new X509Name("cn=test")));
            gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            gen.SetSerialNumber(BigInteger.One);
            gen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

            Target targetName = new Target(
                Target.Choice.Name,
                new GeneralName(GeneralName.DnsName, "www.test.com"));

            Target targetGroup = new Target(
                Target.Choice.Group,
                new GeneralName(GeneralName.DirectoryName, "o=Test, ou=Test"));

            Target[] targets = new Target[] { targetName, targetGroup };

            TargetInformation targetInformation = new TargetInformation(targets);

            gen.AddExtension(X509Extensions.TargetInformation.Id, true, targetInformation);

            return(gen.Generate(privKey));
        }
    public virtual X509Attribute[] GetAttributes()
    {
        Asn1Sequence attributes = cert.ACInfo.Attributes;

        X509Attribute[] array = new X509Attribute[attributes.Count];
        for (int i = 0; i != attributes.Count; i++)
        {
            array[i] = new X509Attribute(attributes[i]);
        }
        return(array);
    }
Exemple #6
0
        Byte[] getHashValue(PkcsSignerInfo signerInfo)
        {
            X509Attribute attr = signerInfo.AuthenticatedAttributes[MESSAGE_DIGEST];

            if (attr == null)
            {
                return(null);
            }
            var asn = new Asn1Reader(attr.RawData);

            return(asn.GetPayload());
        }
Exemple #7
0
        /// <summary>
        /// Attaches a timestamp to signed CMS object.
        /// </summary>
        /// <param name="timestamp">TSP response returned from Time-Stamping Authority.</param>
        /// <param name="signerInfoIndex">Signature index to attach the timestamp.</param>
        /// <exception cref="NotSupportedException">
        /// Time-Stamp Response contains invalid content type.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     Data returned from Time-Stamping Authority does not contain valid response.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     <strong>response</strong> parameter is null.
        /// </exception>
        /// <exception cref="IndexOutOfRangeException">
        ///     <strong>signerInfoIndex</strong> value exceeds the number of attached signatures.
        /// </exception>
        /// <remarks>Call <see cref="Encode"/> method to get timestamped object.</remarks>
        public void AddTimestamp(TspResponse timestamp, Int32 signerInfoIndex)
        {
            if (timestamp == null)
            {
                throw new ArgumentNullException(nameof(timestamp));
            }
            if (timestamp.Status.ResponseStatus != TspResponseStatus.Granted || timestamp.Status.ErrorCode != TspFailureStatus.None)
            {
                throw new ArgumentException("The time-stamp response is not successful.");
            }

            X509Attribute      attribute;
            DefaultSignedPkcs7 tspCms = timestamp.GetSignedCms();

            switch (timestamp.ResponseType.Value)
            {
            case PKCS_7_DATA:
                // add timestamp signing certs to original CMS
                foreach (X509Certificate2 tspCert in tspCms.Certificates)
                {
                    if (!Certificates.Contains(tspCert))
                    {
                        Certificates.Add(tspCert);
                    }
                }
                // for Authenticode timestamp, we add SignerInfo from timestamp CMS
                var asn = new Asn1Reader(tspCms.SignerInfos.Encode());
                attribute = new X509Attribute(new Oid(COUNTER_SIGN), asn.GetPayload());
                break;

            case TST_TOKEN_INFO:
                attribute = new X509Attribute(new Oid(RFC_COUNTER_SIGN), tspCms.RawData);
                break;

            default: throw new NotSupportedException("Time-Stamp response contains invalid content type.");
            }

            var           signerInfoBuilder = new PkcsSignerInfoBuilder(SignerInfos[signerInfoIndex]);
            X509Attribute attr = signerInfoBuilder.UnauthenticatedAttributes[COUNTER_SIGN];

            if (attr != null)
            {
                signerInfoBuilder.UnauthenticatedAttributes.Remove(attr);
            }
            attr = signerInfoBuilder.UnauthenticatedAttributes[RFC_COUNTER_SIGN];
            if (attr != null)
            {
                signerInfoBuilder.UnauthenticatedAttributes.Remove(attr);
            }
            signerInfoBuilder.AddUnauthenticatedAttribute(attribute);
            SignerInfos[signerInfoIndex] = signerInfoBuilder.Encode();
        }
Exemple #8
0
 static void addUniqueAttribute(IList <X509Attribute> referenceList, X509Attribute attribute)
 {
     // if there is already same attribute (with same OID), remove old attribute and add new attribute
     // to avoid duplicates.
     for (Int32 index = 0; index < referenceList.Count; index++)
     {
         if (referenceList[index].Oid.Value == attribute.Oid.Value)
         {
             referenceList.RemoveAt(index);
             break;
         }
     }
     referenceList.Add(attribute);
 }
Exemple #9
0
        void initializeFromSignerInfo(PkcsSignerInfo signerInfo)
        {
            Version           = signerInfo.Version;
            SubjectIdentifier = signerInfo.Issuer.Type;
            signerCert        = signerInfo.Issuer;
            X509Attribute attribute = signerInfo.AuthenticatedAttributes.FirstOrDefault(x => x.Oid.Value == CONTENT_TYPE);

            if (attribute != null)
            {
                ContentType = new Asn1ObjectIdentifier(attribute.RawData).Value;
            }
            pubKeyAlgId = signerInfo.EncryptedHashAlgorithm;
            hashAlgId   = signerInfo.HashAlgorithm;
            hashValue   = signerInfo.EncryptedHash;
            _authAttributes.AddRange(signerInfo.AuthenticatedAttributes);
        }
 /// <summary>
 /// Adds new cryptographic attribute associated with the current certificate trust list item.
 /// </summary>
 /// <param name="attribute">Cryptographic attribute to add.</param>
 /// <exception cref="ArgumentNullException"><strong>attribute</strong> parameter is null.</exception>
 /// <remarks>
 /// If current list of attributes already contains attribute with same OID as in <strong>attribute</strong> parameter,
 /// existing attribute is overwritten with new one. Two or more attributes of same type are not allowed.
 /// </remarks>
 public void AddAttribute(X509Attribute attribute)
 {
     if (attribute == null)
     {
         throw new ArgumentNullException(nameof(attribute));
     }
     // if there is already same attribute (with same OID), remove old attribute and add new attribute
     // to avoid duplicates.
     for (Int32 index = 0; index < _attributes.Count; index++)
     {
         if (_attributes[index].Oid.Value == attribute.Oid.Value)
         {
             _attributes.RemoveAt(index);
             break;
         }
     }
     _attributes.Add(attribute);
 }
Exemple #11
0
        String formatAttributes()
        {
            StringBuilder sb = new StringBuilder();

            if (Attributes.Count == 0)
            {
                return(sb.ToString());
            }

            sb.AppendLine("");
            for (Int32 index = 0; index < Attributes.Count; index++)
            {
                X509Attribute attribute = Attributes[index];
                sb.AppendLine(
                    $"  Attribute[{index}], Length={attribute.RawData.Length} ({attribute.RawData.Length:x2}):");
                sb.AppendLine($"    {attribute.Format(true).Replace("\r\n", "\r\n    ")}");
            }
            return(sb.ToString());
        }
Exemple #12
0
 void getAttributes(Asn1Reader asn)
 {
     asn.MoveNext();
     if (asn.PayloadLength == 0)
     {
         return;
     }
     do
     {
         X509Attribute attribute = X509Attribute.Decode(asn.GetTagRawData());
         if (attribute.Oid.Value == X509CertExtensions.X509CertificateExtensions)
         {
             //Extensions
             Extensions.Decode(attribute.RawData);
         }
         else
         {
             Attributes.Add(attribute);
         }
     } while (asn.MoveNextCurrentLevel());
 }
Exemple #13
0
        public Csr(PrivKey priv, CertificateOptions options)
        {
            X509Name      subject = options.GenerateName();
            GeneralNames  alt     = options.GenerateAltNames();
            X509Extension altName = new X509Extension(false, new DerOctetString(alt));

            List <object> oids = new List <object>()
            {
                X509Extensions.SubjectAlternativeName,
            };

            List <object> values = new List <object>()
            {
                altName,
            };

            X509Extensions x509exts = new X509Extensions(oids, values);
            X509Attribute  attr     = new X509Attribute(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest.Id, new DerSet(x509exts));

            AttributePkcs attr2 = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(x509exts));

            this.Request = new Pkcs10CertificationRequest(new Asn1SignatureFactory(options.GetSignatureAlgorithmOid(), priv.PrivateKeyData.Private, PkiUtil.NewSecureRandom()),
                                                          subject, priv.PublicKey.PublicKeyData, new DerSet(attr2));
        }
    public virtual X509Attribute[] GetAttributes(string oid)
    {
        Asn1Sequence attributes = cert.ACInfo.Attributes;
        IList        list       = Platform.CreateArrayList();

        for (int i = 0; i != attributes.Count; i++)
        {
            X509Attribute x509Attribute = new X509Attribute(attributes[i]);
            if (x509Attribute.Oid.Equals(oid))
            {
                list.Add(x509Attribute);
            }
        }
        if (list.Count < 1)
        {
            return(null);
        }
        X509Attribute[] array = new X509Attribute[list.Count];
        for (int j = 0; j < list.Count; j++)
        {
            array[j] = (X509Attribute)list[j];
        }
        return(array);
    }
 public void AddAttribute(X509Attribute attribute)
 {
     acInfoGen.AddAttribute(AttributeX509.GetInstance(attribute.ToAsn1Object()));
 }
Exemple #16
0
        private void doTestGenerateWithPrincipal()
        {
            X509CertificateParser fact  = new X509CertificateParser();
            X509Certificate       iCert = fact.ReadCertificate(signCert);

            //
            // a sample key pair.
            //
            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16));

            //
            // set up the keys
            //
//			PrivateKey          privKey;
//			PublicKey           pubKey;
//
//			KeyFactory  kFact = KeyFactory.getInstance("RSA");
//
//			privKey = kFact.generatePrivate(RSA_PRIVATE_KEY_SPEC);
//			pubKey = kFact.generatePublic(pubKeySpec);
            AsymmetricKeyParameter privKey = RSA_PRIVATE_KEY_SPEC;

            X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator();

            // the actual attributes
            GeneralName roleName = new GeneralName(GeneralName.Rfc822Name, "DAU123456789");

            // roleSyntax OID: 2.5.24.72
            X509Attribute attributes = new X509Attribute("2.5.24.72",
                                                         new DerSequence(roleName));

            gen.AddAttribute(attributes);
            gen.SetHolder(new AttributeCertificateHolder(iCert.SubjectDN));
            gen.SetIssuer(new AttributeCertificateIssuer(new X509Name("cn=test")));
            gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            gen.SetSerialNumber(BigInteger.One);
            gen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

            IX509AttributeCertificate aCert = gen.Generate(privKey);

            aCert.CheckValidity();

            aCert.Verify(pubKey);

            AttributeCertificateHolder holder = aCert.Holder;

            if (holder.GetEntityNames() == null)
            {
                Fail("entity names not set when expected");
            }

            if (holder.SerialNumber != null)
            {
                Fail("holder serial number found when none expected");
            }

            if (holder.GetIssuer() != null)
            {
                Fail("holder issuer found when none expected");
            }

            if (!holder.Match(iCert))
            {
                Fail("generated holder not matching holder certificate");
            }

            X509Certificate sCert = fact.ReadCertificate(holderCertWithBaseCertificateID);

            if (holder.Match(sCert))
            {
                Fail("principal generated holder matching wrong certificate");
            }

            equalityAndHashCodeTest(aCert, aCert.GetEncoded());
        }