示例#1
0
        public TimeStampTokenGenerator(AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID, Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttr, Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttr)
        {
            this.key          = key;
            this.cert         = cert;
            this.digestOID    = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;
            TspUtil.ValidateCertificate(cert);
            IDictionary dictionary;

            if (signedAttr != null)
            {
                dictionary = signedAttr.ToDictionary();
            }
            else
            {
                dictionary = Platform.CreateHashtable();
            }
            try
            {
                byte[]    hash      = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());
                EssCertID essCertID = new EssCertID(hash);
                Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(new SigningCertificate(essCertID)));
                dictionary[attribute.AttrType] = attribute;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }
            catch (SecurityUtilityException e2)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e2);
            }
            this.signedAttr = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
        }
 public EssCertID[] GetCerts()
 {
     EssCertID[] array = new EssCertID[certs.Count];
     for (int i = 0; i != certs.Count; i++)
     {
         array[i] = EssCertID.GetInstance(certs[i]);
     }
     return(array);
 }
        public TimeStampToken(
            CmsSignedData signedData)
        {
            this.tsToken = signedData;

            if (!this.tsToken.SignedContentTypeOid.Equals(PkcsObjectIdentifiers.IdCTTstInfo.Id))
            {
                throw new TspValidationException("ContentInfo object not for a time stamp.");
            }

            ICollection signers = tsToken.GetSignerInfos().GetSigners();

            if (signers.Count != 1)
            {
                throw new ArgumentException("Time-stamp token signed by "
                                            + signers.Count
                                            + " signers, but it must contain just the TSA signature.");
            }


            IEnumerator signerEnum = signers.GetEnumerator();

            signerEnum.MoveNext();
            tsaSignerInfo = (SignerInformation)signerEnum.Current;

            try
            {
                CmsProcessable content = tsToken.SignedContent;
                MemoryStream   bOut    = new MemoryStream();

                content.Write(bOut);

                this.tstInfo = new TimeStampTokenInfo(
                    TstInfo.GetInstance(
                        Asn1Object.FromByteArray(bOut.ToArray())));

                Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[
                    PkcsObjectIdentifiers.IdAASigningCertificate];

                if (attr == null)
                {
                    throw new TspValidationException(
                              "no signing certificate attribute found, time stamp invalid.");
                }

                SigningCertificate signCert = SigningCertificate.GetInstance(
                    attr.AttrValues[0]);

                this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]);
            }
            catch (CmsException e)
            {
                throw new TspException(e.Message, e.InnerException);
            }
        }
示例#4
0
        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
            AsymmetricKeyParameter key,
            X509Certificate cert,
            string digestOID,
            string tsaPolicyOID,
            Asn1.Cms.AttributeTable signedAttr,
            Asn1.Cms.AttributeTable unsignedAttr)
        {
            this.key          = key;
            this.cert         = cert;
            this.digestOID    = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // Add the ESSCertID attribute
            //
            Hashtable signedAttrs;

            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToHashtable();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            try
            {
                byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }
            catch (SecurityUtilityException e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }
    public TimeStampToken(CmsSignedData signedData)
    {
        tsToken = signedData;
        if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo))
        {
            throw new TspValidationException("ContentInfo object not for a time stamp.");
        }
        ICollection signers = tsToken.GetSignerInfos().GetSigners();

        if (signers.Count != 1)
        {
            throw new ArgumentException("Time-stamp token signed by " + signers.Count + " signers, but it must contain just the TSA signature.");
        }
        IEnumerator enumerator = signers.GetEnumerator();

        enumerator.MoveNext();
        tsaSignerInfo = (SignerInformation)enumerator.Current;
        try
        {
            CmsProcessable signedContent = tsToken.SignedContent;
            MemoryStream   memoryStream  = new MemoryStream();
            signedContent.Write(memoryStream);
            tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(memoryStream.ToArray())));
            Org.BouncyCastle.Asn1.Cms.Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
            if (attribute != null)
            {
                SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]);
                certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0]));
            }
            else
            {
                attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
                if (attribute == null)
                {
                    throw new TspValidationException("no signing certificate attribute found, time stamp invalid.");
                }
                SigningCertificateV2 instance2 = SigningCertificateV2.GetInstance(attribute.AttrValues[0]);
                certID = new CertID(EssCertIDv2.GetInstance(instance2.GetCerts()[0]));
            }
        }
        catch (CmsException ex)
        {
            throw new TspException(ex.Message, ex.InnerException);
        }
    }
示例#6
0
 public TimeStampToken(CmsSignedData signedData)
 {
     //IL_0063: Unknown result type (might be due to invalid IL or missing references)
     //IL_0094: Unknown result type (might be due to invalid IL or missing references)
     //IL_009a: Expected O, but got Unknown
     tsToken = signedData;
     if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo))
     {
         throw new TspValidationException("ContentInfo object not for a time stamp.");
     }
     global::System.Collections.ICollection signers = tsToken.GetSignerInfos().GetSigners();
     if (signers.get_Count() != 1)
     {
         throw new ArgumentException(string.Concat((object)"Time-stamp token signed by ", (object)signers.get_Count(), (object)" signers, but it must contain just the TSA signature."));
     }
     global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)signers).GetEnumerator();
     enumerator.MoveNext();
     tsaSignerInfo = (SignerInformation)enumerator.get_Current();
     try
     {
         CmsProcessable signedContent = tsToken.SignedContent;
         MemoryStream   val           = new MemoryStream();
         signedContent.Write((Stream)(object)val);
         tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(val.ToArray())));
         Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
         if (attribute != null)
         {
             SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]);
             certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0]));
             return;
         }
         attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
         if (attribute == null)
         {
             throw new TspValidationException("no signing certificate attribute found, time stamp invalid.");
         }
         SigningCertificateV2 instance2 = SigningCertificateV2.GetInstance(attribute.AttrValues[0]);
         certID = new CertID(EssCertIDv2.GetInstance(instance2.GetCerts()[0]));
     }
     catch (CmsException ex)
     {
         throw new TspException(((global::System.Exception)ex).get_Message(), ((global::System.Exception)ex).get_InnerException());
     }
 }
 internal CertID(EssCertIDv2 certID)
 {
     this.certIDv2 = certID;
     this.certID   = null;
 }
 public SigningCertificate(EssCertID essCertID)
 {
     certs = new DerSequence(essCertID);
 }
示例#9
0
        public TimeStampTokenGenerator(
            SignerInfoGenerator signerInfoGen,
            IDigestFactory digestCalculator,
            DerObjectIdentifier tsaPolicy,
            bool isIssuerSerialIncluded)
        {
            this.signerInfoGenerator = signerInfoGen;
            this.digestCalculator    = digestCalculator;
            this.tsaPolicyOID        = tsaPolicy != null ? tsaPolicy.Id : null;

            if (signerInfoGenerator.certificate == null)
            {
                throw new ArgumentException("SignerInfoGenerator must have an associated certificate");
            }

            X509Certificate assocCert = signerInfoGenerator.certificate;

            TspUtil.ValidateCertificate(assocCert);

            try
            {
                IStreamCalculator calculator = digestCalculator.CreateCalculator();
                Stream            stream     = calculator.Stream;
                byte[]            certEnc    = assocCert.GetEncoded();
                stream.Write(certEnc, 0, certEnc.Length);
                stream.Flush();
                stream.Close();

                if (((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm.Equals(OiwObjectIdentifiers.IdSha1))
                {
                    EssCertID essCertID = new EssCertID(
                        ((IBlockResult)calculator.GetResult()).Collect(),
                        isIssuerSerialIncluded ?
                        new IssuerSerial(
                            new GeneralNames(
                                new GeneralName(assocCert.IssuerDN)),
                            new DerInteger(assocCert.SerialNumber)) : null);

                    this.signerInfoGenerator = signerInfoGen.NewBuilder()
                                               .WithSignedAttributeGenerator(new TableGen(signerInfoGen, essCertID))
                                               .Build(signerInfoGen.contentSigner, signerInfoGen.certificate);
                }
                else
                {
                    AlgorithmIdentifier digestAlgID = new AlgorithmIdentifier(
                        ((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm);

                    EssCertIDv2 essCertID = new EssCertIDv2(
                        ((IBlockResult)calculator.GetResult()).Collect(),
                        isIssuerSerialIncluded ?
                        new IssuerSerial(
                            new GeneralNames(
                                new GeneralName(assocCert.IssuerDN)),
                            new DerInteger(assocCert.SerialNumber)) : null);

                    this.signerInfoGenerator = signerInfoGen.NewBuilder()
                                               .WithSignedAttributeGenerator(new TableGen2(signerInfoGen, essCertID))
                                               .Build(signerInfoGen.contentSigner, signerInfoGen.certificate);
                }
            }
            catch (Exception ex)
            {
                throw new TspException("Exception processing certificate", ex);
            }
        }
示例#10
0
 public TableGen(SignerInfoGenerator infoGen, EssCertID essCertID)
 {
     this.infoGen   = infoGen;
     this.essCertID = essCertID;
 }
示例#11
0
        private void ReadInformation()
        {
            if (_signerInformation.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime] != null)
            {
                _signingDate = DerUtcTime.GetInstance(_signerInformation.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime].AttrValues[0]).ToDateTime().ToLocalTime();
            }

            if (_signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAAEtsSignerAttr] != null)
            {
                var signerAttr = SignerAttribute.GetInstance(_signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAAEtsSignerAttr].AttrValues[0]);

                List <string> claimedRoles = new List <string>();

                foreach (BcCms.Attribute claimedAttr in signerAttr.ClaimedAttributes)
                {
                    foreach (var value in claimedAttr.AttrValues)
                    {
                        claimedRoles.Add(DerUtf8String.GetInstance(value).GetString());
                    }
                }

                _signerRoles = claimedRoles;
            }

            if (_signerInformation.UnsignedAttributes != null &&
                _signerInformation.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] != null)
            {
                _timeStamp = new TimeStampToken(new CmsSignedData(_signerInformation.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrValues[0].GetEncoded()));
            }

            // Se leen las contrafirmas
            var signers = _signerInformation.GetCounterSignatures().GetSigners();

            _counterSignatures = new List <SignerInfoNode>();

            foreach (var signer in signers)
            {
                SignerInfoNode node = new SignerInfoNode((SignerInformation)signer, _sigDocument);

                _counterSignatures.Add(node);
            }

            // Se intenta identificar el certificado empleado para la firma, esto quizás se pueda mejorar
            byte[]       certHash     = null;
            IssuerSerial issuerSerial = null;

            if (_signerInformation.DigestAlgOid == DigestMethod.SHA1.Oid)
            {
                BcCms.Attribute    attr = _signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
                SigningCertificate sc   = SigningCertificate.GetInstance(attr.AttrValues[0]);
                EssCertID          ecid = sc.GetCerts()[0];
                issuerSerial = ecid.IssuerSerial;
                certHash     = ecid.GetCertHash();
            }
            else
            {
                BcCms.Attribute      attr = _signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
                SigningCertificateV2 sc2  = SigningCertificateV2.GetInstance(attr.AttrValues[0]);
                EssCertIDv2          ecid = sc2.GetCerts()[0];
                issuerSerial = ecid.IssuerSerial;
                certHash     = ecid.GetCertHash();
            }

            DigestMethod digestMethod = DigestMethod.GetByOid(_signerInformation.DigestAlgOid);

            foreach (X509CertificateStructure cs in _sigDocument.Certificates)
            {
                if (issuerSerial == null || cs.TbsCertificate.SerialNumber.Equals(issuerSerial.Serial))
                {
                    byte[] currentCertHash = digestMethod.CalculateDigest(cs.GetEncoded());

                    if (certHash.SequenceEqual(currentCertHash))
                    {
                        _certificate = new X509Certificate(cs);
                        break;
                    }
                }
            }
        }
 internal CertID(EssCertID certID)
 {
     this.certID = certID;
     certIDv2    = null;
 }
示例#13
0
        public static Asn1EncodableVector GenerateSignerInfo(X509Certificate2 cert,
                                                             String digestAlgorithmName,
                                                             byte[] datos,
                                                             AdESPolicy policy,
                                                             bool signingCertificateV2,
                                                             byte[] messageDigest,
                                                             DateTime signDate,
                                                             bool padesMode,
                                                             String contentType,
                                                             String contentDescription)
        {
            // ALGORITMO DE HUELLA DIGITAL
            AlgorithmIdentifier digestAlgorithmOID = SigUtils.MakeAlgId(AOAlgorithmID.GetOID(digestAlgorithmName));

            // // ATRIBUTOS

            // authenticatedAttributes
            Asn1EncodableVector contexExpecific = InitContexExpecific(
                digestAlgorithmName,
                datos,
                Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id,
                messageDigest,
                signDate,
                padesMode
                );

            // Serial Number
            // comentar lo de abajo para version del rfc 3852

            if (signingCertificateV2)
            {
                // INICIO SINGING CERTIFICATE-V2

                /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
                 * CertificateSerialNumber */



                TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(
                        new Org.BouncyCastle.X509.X509Certificate(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(
                                    cert.GetRawCertData()))).GetTbsCertificate()));

                GeneralNames gns = new GeneralNames(new GeneralName(tbs.Issuer));

                IssuerSerial isuerSerial = new IssuerSerial(gns, tbs.SerialNumber);

                /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier
                 * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial
                 * IssuerSerial OPTIONAL }
                 * Hash ::= OCTET STRING */

                byte[]        certHash    = Digester.Digest(cert.GetRawCertData(), digestAlgorithmName);
                EssCertIDv2[] essCertIDv2 = { new EssCertIDv2(digestAlgorithmOID, certHash, isuerSerial) };

                /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
                 * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
                 * OPTIONAL }
                 * CertPolicyId ::= OBJECT IDENTIFIER
                 * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
                 * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

                SigningCertificateV2 scv2;
                if (policy.GetPolicyIdentifier() != null)
                {
                    /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
                     * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
                     * } */
                    scv2 = new SigningCertificateV2(essCertIDv2, GetPolicyInformation(policy)); // con politica
                }
                else
                {
                    scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica
                }

                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2)));

                // FIN SINGING CERTIFICATE-V2
            }
            else
            {
                // INICIO SINGNING CERTIFICATE

                /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
                 * CertificateSerialNumber } */

                TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(
                        new Org.BouncyCastle.X509.X509Certificate(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(
                                    cert.GetRawCertData()))).GetTbsCertificate()));

                GeneralName  gn  = new GeneralName(tbs.Issuer);
                GeneralNames gns = new GeneralNames(gn);

                IssuerSerial isuerSerial = new IssuerSerial(gns, tbs.SerialNumber);

                /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial
                 * OPTIONAL }
                 * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */
                byte[] certHash = Digester.Digest(cert.GetRawCertData(), digestAlgorithmName);

                EssCertID essCertID = new EssCertID(certHash, isuerSerial);

                /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
                 * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
                 * OPTIONAL }
                 * CertPolicyId ::= OBJECT IDENTIFIER
                 * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
                 * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

                SigningCertificate scv;
                if (policy.GetPolicyIdentifier() != null)
                {
                    /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
                     * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
                     * } */
                    /*
                     * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY
                     * CASTLE NO TIENE DICHO CONSTRUCTOR.
                     */
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    v.Add(new DerSequence(essCertID));
                    v.Add(new DerSequence(GetPolicyInformation(policy)));
                    scv = SigningCertificate.GetInstance(new DerSequence(v)); // con politica
                }
                else
                {
                    scv = new SigningCertificate(essCertID); // Sin politica
                }

                /** id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
                 * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16)
                 * id-aa(2) 12 } */
                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(scv)));
            }

            // INICIO SIGPOLICYID ATTRIBUTE

            if (policy.GetPolicyIdentifier() != null)
            {
                /**
                 * SigPolicyId ::= OBJECT IDENTIFIER Politica de firma.
                 */
                DerObjectIdentifier doiSigPolicyId = new DerObjectIdentifier(policy.GetPolicyIdentifier().ToLower().Replace("urn:oid:", ""));

                /**
                 *   OtherHashAlgAndValue ::= SEQUENCE {
                 *     hashAlgorithm    AlgorithmIdentifier,
                 *     hashValue        OCTET STRING }
                 *
                 */


                // Algoritmo para el hash
                AlgorithmIdentifier hashid;
                // si tenemos algoritmo de calculo de hash, lo ponemos
                if (policy.GetPolicyIdentifierHashAlgorithm() != null)
                {
                    hashid = SigUtils.MakeAlgId(
                        AOAlgorithmID.GetOID(
                            AOSignConstants.GetDigestAlgorithmName(
                                policy.GetPolicyIdentifierHashAlgorithm())));
                }
                // si no tenemos, ponemos el algoritmo de firma.
                else
                {
                    hashid = digestAlgorithmOID;
                }
                // hash del documento, descifrado en b64
                byte[] hashed;
                if (policy.GetPolicyIdentifierHash() != null)
                {
                    hashed = System.Convert.FromBase64String(policy.GetPolicyIdentifierHash());
                }
                else
                {
                    hashed = new byte[] { 0 };
                }

                DigestInfo otherHashAlgAndValue = new DigestInfo(hashid, hashed);

                /**
                 *   SigPolicyQualifierInfo ::= SEQUENCE {
                 *       SigPolicyQualifierId  SigPolicyQualifierId,
                 *       SigQualifier          ANY DEFINED BY policyQualifierId }
                 */

                AOSigPolicyQualifierInfo spqInfo = null;
                if (policy.GetPolicyQualifier() != null)
                {
                    spqInfo = new AOSigPolicyQualifierInfo(policy.GetPolicyQualifier().ToString());
                }

                /**
                 * SignaturePolicyId ::= SEQUENCE {
                 *  sigPolicyId           SigPolicyId,
                 *  sigPolicyHash         SigPolicyHash,
                 *  sigPolicyQualifiers   SEQUENCE SIZE (1..MAX) OF
                 *                          AOSigPolicyQualifierInfo OPTIONAL}
                 *
                 */
                Asn1EncodableVector v = new Asn1EncodableVector();
                // sigPolicyId
                v.Add(doiSigPolicyId);
                // sigPolicyHash
                v.Add(otherHashAlgAndValue.ToAsn1Object()); // como sequence
                // sigPolicyQualifiers
                if (spqInfo != null)
                {
                    v.Add(spqInfo.toASN1Primitive());
                }

                DerSequence ds = new DerSequence(v);

                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAEtsSigPolicyID, new DerSet(ds.ToAsn1Object())));
                // FIN SIGPOLICYID ATTRIBUTE
            }

            /**
             * Secuencia con el tipo de contenido firmado. No se agrega en firmas PAdES.
             *
             * ContentHints ::= SEQUENCE {
             *	  contentDescription UTF8String (SIZE (1..MAX)) OPTIONAL,
             *	  contentType ContentType }
             */
            if (contentType != null && !padesMode)
            {
                ContentHints contentHints;
                if (contentDescription != null)
                {
                    contentHints = new ContentHints(new DerObjectIdentifier(contentType),
                                                    new DerUtf8String(contentDescription));
                }
                else
                {
                    contentHints = new ContentHints(new DerObjectIdentifier(contentType));
                }
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(
                                        Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAContentHint,
                                        new DerSet(contentHints.ToAsn1Object())));
            }

            return(contexExpecific);
        }
 public TestAttrGen(EssCertID essCertID, EssCertIDv2 essCertIDv2)
 {
     this.mEssCertID   = essCertID;
     this.mEssCertIDv2 = essCertIDv2;
 }
        private void overrideAttrsTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            SignerInfoGeneratorBuilder signerInfoGenBuilder = new SignerInfoGeneratorBuilder();

            IssuerSerial issuerSerial = new IssuerSerial(
                new GeneralNames(
                    new GeneralName(
                        X509CertificateStructure.GetInstance(cert.GetEncoded()).Issuer)),
                new DerInteger(cert.SerialNumber));

            byte[] certHash256;
            byte[] certHash;

            {
                Asn1DigestFactory digCalc = Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1);
                IStreamCalculator calc    = digCalc.CreateCalculator();
                using (Stream s = calc.Stream)
                {
                    byte[] crt = cert.GetEncoded();
                    s.Write(crt, 0, crt.Length);
                }

                certHash = ((SimpleBlockResult)calc.GetResult()).Collect();
            }


            {
                Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256);
                IStreamCalculator calc    = digCalc.CreateCalculator();
                using (Stream s = calc.Stream)
                {
                    byte[] crt = cert.GetEncoded();
                    s.Write(crt, 0, crt.Length);
                }

                certHash256 = ((SimpleBlockResult)calc.GetResult()).Collect();
            }


            EssCertID   essCertID   = new EssCertID(certHash, issuerSerial);
            EssCertIDv2 essCertIDv2 = new EssCertIDv2(certHash256, issuerSerial);

            signerInfoGenBuilder.WithSignedAttributeGenerator(new TestAttrGen(essCertID, essCertIDv2));


            Asn1SignatureFactory sigfact             = new Asn1SignatureFactory("SHA1WithRSA", privateKey);
            SignerInfoGenerator  signerInfoGenerator = signerInfoGenBuilder.Build(sigfact, cert);

            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(signerInfoGenerator,
                                                                             Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1), new DerObjectIdentifier("1.2"), true);

            tsTokenGen.SetCertificates(certs);


            TimeStampRequestGenerator reqGen  = new TimeStampRequestGenerator();
            TimeStampRequest          request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100));

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");
            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificateV2], "no signingCertificateV2 attribute found");

            SigningCertificate sigCert = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificate].AttrValues[0]);

            Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCert.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name));
            Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCert.GetCerts()[0].IssuerSerial.Serial.Value));
            Assert.IsTrue(Arrays.AreEqual(certHash, sigCert.GetCerts()[0].GetCertHash()));

            SigningCertificate sigCertV2 = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]);

            Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name));
            Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Serial.Value));
            Assert.IsTrue(Arrays.AreEqual(certHash256, sigCertV2.GetCerts()[0].GetCertHash()));
        }