예제 #1
0
        private X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer, IEnumerable <string> ocspServers, FirmaXades.Crypto.DigestMethod digestMethod)
        {
            bool          byKey = false;
            List <string> list  = new List <string>();

            Org.BouncyCastle.X509.X509Certificate eeCert          = client.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate x509Certificate = issuer.ToBouncyX509Certificate();
            OcspClient ocspClient = new OcspClient();
            string     authorityInformationAccessOcspUrl = ocspClient.GetAuthorityInformationAccessOcspUrl(x509Certificate);

            if (!string.IsNullOrEmpty(authorityInformationAccessOcspUrl))
            {
                list.Add(authorityInformationAccessOcspUrl);
            }
            foreach (string ocspServer in ocspServers)
            {
                list.Add(ocspServer);
            }
            foreach (string item in list)
            {
                byte[] array = ocspClient.QueryBinary(eeCert, x509Certificate, item);
                switch (ocspClient.ProcessOcspResponse(array))
                {
                case FirmaXades.Clients.CertificateStatus.Revoked:
                    throw new Exception("Certificado revocado");

                case FirmaXades.Clients.CertificateStatus.Good:
                {
                    OcspResp      ocspResp      = new OcspResp(array);
                    byte[]        encoded       = ocspResp.GetEncoded();
                    BasicOcspResp basicOcspResp = (BasicOcspResp)ocspResp.GetResponseObject();
                    string        str           = Guid.NewGuid().ToString();
                    OCSPRef       oCSPRef       = new OCSPRef();
                    oCSPRef.OCSPIdentifier.UriAttribute = "#OcspValue" + str;
                    DigestUtil.SetCertDigest(encoded, digestMethod, oCSPRef.CertDigest);
                    ResponderID responderId   = basicOcspResp.ResponderId.ToAsn1Object();
                    string      responderName = GetResponderName(responderId, ref byKey);
                    if (!byKey)
                    {
                        oCSPRef.OCSPIdentifier.ResponderID = RevertIssuerName(responderName);
                    }
                    else
                    {
                        oCSPRef.OCSPIdentifier.ResponderID = responderName;
                        oCSPRef.OCSPIdentifier.ByKey       = true;
                    }
                    oCSPRef.OCSPIdentifier.ProducedAt = basicOcspResp.ProducedAt.ToLocalTime();
                    unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.OCSPRefs.OCSPRefCollection.Add(oCSPRef);
                    OCSPValue oCSPValue = new OCSPValue();
                    oCSPValue.PkiData = encoded;
                    oCSPValue.Id      = "OcspValue" + str;
                    unsignedProperties.UnsignedSignatureProperties.RevocationValues.OCSPValues.OCSPValueCollection.Add(oCSPValue);
                    return((from cert in basicOcspResp.GetCerts()
                            select new X509Certificate2(cert.GetEncoded())).ToArray());
                }
                }
            }
            throw new Exception("El certificado no ha podido ser validado");
        }
예제 #2
0
        /// <summary>
        /// Insert the certificate in the certificate list and check the certificate validity.
        /// </summary>
        /// <param name="cert"></param>
        /// <param name="unsignedProperties"></param>
        /// <param name="addCert"></param>
        /// <param name="ocspServers"></param>
        /// <param name="crlList"></param>
        /// <param name="digestMethod"></param>
        /// <param name="addCertificateOcspUrl"></param>
        /// <param name="extraCerts"></param>
        /// <param name="useNonce">If true then nonce will be used. The ocsp server should support this. OCSP reposnder in Microsoft Windows must be configured explicitly to support nonce.</param>
        private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, IEnumerable <OcspServer> ocspServers,
                                    IEnumerable <X509Crl> crlList, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl, X509Certificate2[] extraCerts = null, bool useNonce = true)
        {
            if (addCert)
            {
                if (CertificateChecked(cert, unsignedProperties))
                {
                    return;
                }

                string guidCert = Guid.NewGuid().ToString();

                Cert chainCert = new Cert();
                chainCert.IssuerSerial.X509IssuerName   = cert.IssuerName.Name;
                chainCert.IssuerSerial.X509SerialNumber = cert.GetSerialNumberAsDecimalString();
                DigestUtil.SetCertDigest(cert.GetRawCertData(), digestMethod, chainCert.CertDigest);
                chainCert.URI = "#Cert" + guidCert;
                unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(chainCert);

                EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate
                {
                    Id      = "Cert" + guidCert,
                    PkiData = cert.GetRawCertData()
                };
                unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate);
            }

            var chain = CertUtil.GetCertChain(cert, extraCerts).ChainElements;

            if (chain.Count > 1)
            {
                X509ChainElementEnumerator enumerator = chain.GetEnumerator();
                enumerator.MoveNext(); // el mismo certificado que el pasado por parametro

                enumerator.MoveNext();

                bool valid = ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate, crlList, digestMethod);

                if (!valid)
                {
                    var ocspCerts = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate, ocspServers, digestMethod, addCertificateOcspUrl, useNonce);

                    if (ocspCerts != null)
                    {
                        X509Certificate2 startOcspCert = DetermineStartCert(ocspCerts);

                        if (!EquivalentDN(startOcspCert.IssuerName, enumerator.Current.Certificate.SubjectName))
                        {
                            var chainOcsp = CertUtil.GetCertChain(startOcspCert, ocspCerts);

                            AddCertificate(chainOcsp.ChainElements[1].Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, addCertificateOcspUrl, ocspCerts);
                        }
                    }
                }

                AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, addCertificateOcspUrl, extraCerts);
            }
        }
예제 #3
0
        private void AddSignatureProperties(SignatureDocument sigDocument, SignedSignatureProperties signedSignatureProperties, SignedDataObjectProperties signedDataObjectProperties, UnsignedSignatureProperties unsignedSignatureProperties, SignatureParameters parameters)
        {
            var certificateIssuerName = !string.IsNullOrEmpty(parameters.CertificateIssuerName) ?
                                        parameters.CertificateIssuerName : createValidIssuerName(parameters.Signer.Certificate);

            Cert cert = new Cert();

            cert.IssuerSerial.X509IssuerName   = certificateIssuerName;
            cert.IssuerSerial.X509SerialNumber = parameters.Signer.Certificate.GetSerialNumberAsDecimalString();
            DigestUtil.SetCertDigest(parameters.Signer.Certificate.GetRawCertData(), parameters.DigestMethod, cert.CertDigest);
            signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);
            if (parameters.SignaturePolicyInfo != null)
            {
                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyIdentifier))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = false;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyId.Identifier.IdentifierUri = parameters.SignaturePolicyInfo.PolicyIdentifier;
                }
                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyDescription))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyId.Description = parameters.SignaturePolicyInfo.PolicyDescription;
                }
                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyUri))
                {
                    SigPolicyQualifier sigPolicyQualifier = new SigPolicyQualifier();
                    sigPolicyQualifier.AnyXmlElement           = sigDocument.Document.CreateElement("SPURI", "http://uri.etsi.org/01903/v1.3.2#");
                    sigPolicyQualifier.AnyXmlElement.InnerText = parameters.SignaturePolicyInfo.PolicyUri;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyQualifiers.SigPolicyQualifierCollection.Add(sigPolicyQualifier);
                }
                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyHash))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestMethod.Algorithm = parameters.SignaturePolicyInfo.PolicyDigestAlgorithm.URI;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestValue            = Convert.FromBase64String(parameters.SignaturePolicyInfo.PolicyHash);
                }
            }
            signedSignatureProperties.SigningTime = (parameters.SigningDate.HasValue ? parameters.SigningDate.Value : DateTime.Now);

            if (parameters.SignerRole != null && (parameters.SignerRole.CertifiedRoles.Count > 0 || parameters.SignerRole.ClaimedRoles.Count > 0))
            {
                signedSignatureProperties.SignerRole = new Microsoft.Xades.SignerRole();
                foreach (X509Certificate certifiedRole in parameters.SignerRole.CertifiedRoles)
                {
                    signedSignatureProperties.SignerRole.CertifiedRoles.CertifiedRoleCollection.Add(new CertifiedRole
                    {
                        PkiData = certifiedRole.GetRawCertData()
                    });
                }
                foreach (string claimedRole in parameters.SignerRole.ClaimedRoles)
                {
                    signedSignatureProperties.SignerRole.ClaimedRoles.ClaimedRoleCollection.Add(new ClaimedRole
                    {
                        InnerText = claimedRole
                    });
                }
            }
        }
예제 #4
0
        /// <summary>
        /// Inserta en la lista de certificados el certificado y comprueba la valided del certificado.
        /// </summary>
        /// <param name="cert"></param>
        /// <param name="unsignedProperties"></param>
        /// <param name="addCertValue"></param>
        /// <param name="extraCerts"></param>
        private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, X509Certificate2[] extraCerts = null)
        {
            if (addCert)
            {
                if (CertificateChecked(cert, unsignedProperties))
                {
                    return;
                }

                string guidCert = Guid.NewGuid().ToString();

                Cert chainCert = new Cert();
                chainCert.IssuerSerial.X509IssuerName   = cert.IssuerName.Name;
                chainCert.IssuerSerial.X509SerialNumber = CertUtil.HexToDecimal(cert.SerialNumber);
                DigestUtil.SetCertDigest(cert.GetRawCertData(), _firma.RefsDigestMethod, chainCert.CertDigest);
                chainCert.URI = "#Cert" + guidCert;
                unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(chainCert);

                EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate();
                encapsulatedX509Certificate.Id      = "Cert" + guidCert;
                encapsulatedX509Certificate.PkiData = cert.GetRawCertData();
                unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate);
            }

            var chain = CertUtil.GetCertChain(cert, extraCerts).ChainElements;

            if (chain.Count > 1)
            {
                X509ChainElementEnumerator enumerator = chain.GetEnumerator();
                enumerator.MoveNext(); // el mismo certificado que el pasado por parametro

                enumerator.MoveNext();

                bool valid = ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate);

                if (!valid)
                {
                    var ocspCerts = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate);

                    if (ocspCerts != null)
                    {
                        X509Certificate2 startOcspCert = DetermineStartCert(new List <X509Certificate2>(ocspCerts));

                        if (startOcspCert.IssuerName.Name != enumerator.Current.Certificate.SubjectName.Name)
                        {
                            var chainOcsp = CertUtil.GetCertChain(startOcspCert, ocspCerts);

                            AddCertificate(chainOcsp.ChainElements[1].Certificate, unsignedProperties, true, ocspCerts);
                        }
                    }
                }

                AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, extraCerts);
            }
        }
예제 #5
0
        private bool ValidateCertificateByCRL(UnsignedProperties unsignedProperties, X509Certificate2 certificate, X509Certificate2 issuer,
                                              IEnumerable <X509Crl> crlList, FirmaXadesNet.Crypto.DigestMethod digestMethod)
        {
            Org.BouncyCastle.X509.X509Certificate clientCert = certificate.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate issuerCert = issuer.ToBouncyX509Certificate();

            foreach (var crlEntry in crlList)
            {
                if (crlEntry.IssuerDN.Equivalent(issuerCert.SubjectDN) && crlEntry.NextUpdate.Value > DateTime.Now)
                {
                    if (!crlEntry.IsRevoked(clientCert))
                    {
                        if (!ExistsCRL(unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection,
                                       issuer.Subject))
                        {
                            string idCrlValue = "CRLValue-" + Guid.NewGuid().ToString();

                            CRLRef crlRef = new CRLRef();
                            crlRef.CRLIdentifier.UriAttribute = "#" + idCrlValue;
                            crlRef.CRLIdentifier.Issuer       = issuer.Subject;
                            crlRef.CRLIdentifier.IssueTime    = crlEntry.ThisUpdate.ToLocalTime();

                            var crlNumber = GetCRLNumber(crlEntry);
                            if (crlNumber.HasValue)
                            {
                                crlRef.CRLIdentifier.Number = crlNumber.Value;
                            }

                            byte[] crlEncoded = crlEntry.GetEncoded();
                            DigestUtil.SetCertDigest(crlEncoded, digestMethod, crlRef.CertDigest);

                            CRLValue crlValue = new CRLValue
                            {
                                PkiData = crlEncoded,
                                Id      = idCrlValue
                            };

                            unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection.Add(crlRef);
                            unsignedProperties.UnsignedSignatureProperties.RevocationValues.CRLValues.CRLValueCollection.Add(crlValue);
                        }

                        return(true);
                    }
                    else
                    {
                        throw new Exception("Certificate revoked");
                    }
                }
            }

            return(false);
        }
예제 #6
0
        private void AddSignatureProperties(SignatureDocument sigDocument, SignedSignatureProperties signedSignatureProperties, SignedDataObjectProperties signedDataObjectProperties,
                                            UnsignedSignatureProperties unsignedSignatureProperties, SignatureParameters parameters)
        {
            Cert cert;

            cert = new Cert();
            cert.IssuerSerial.X509IssuerName   = parameters.Signer.Certificate.IssuerName.Name;
            cert.IssuerSerial.X509SerialNumber = parameters.Signer.Certificate.GetSerialNumberAsDecimalString();
            DigestUtil.SetCertDigest(parameters.Signer.Certificate.GetRawCertData(), parameters.DigestMethod, cert.CertDigest);
            signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);

            if (parameters.SignaturePolicyInfo != null)
            {
                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyIdentifier))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = false;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyId.Identifier.IdentifierUri = parameters.SignaturePolicyInfo.PolicyIdentifier;
                }

                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyUri))
                {
                    SigPolicyQualifier spq = new SigPolicyQualifier();
                    spq.AnyXmlElement           = sigDocument.Document.CreateElement("SPURI", XadesSignedXml.XadesNamespaceUri);
                    spq.AnyXmlElement.InnerText = parameters.SignaturePolicyInfo.PolicyUri;

                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyQualifiers.SigPolicyQualifierCollection.Add(spq);
                }

                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyHash))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestMethod.Algorithm = parameters.SignaturePolicyInfo.PolicyDigestAlgorithm.URI;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestValue            = Convert.FromBase64String(parameters.SignaturePolicyInfo.PolicyHash);
                }
            }

            signedSignatureProperties.SigningTime = parameters.SigningDate.HasValue ? parameters.SigningDate.Value : DateTime.Now;

            if (!string.IsNullOrEmpty(_mimeType))
            {
                DataObjectFormat newDataObjectFormat = new DataObjectFormat();

                newDataObjectFormat.MimeType = _mimeType;
                newDataObjectFormat.Encoding = _encoding;
                newDataObjectFormat.ObjectReferenceAttribute = "#" + _refContent.Id;

                signedDataObjectProperties.DataObjectFormatCollection.Add(newDataObjectFormat);
            }
        }
예제 #7
0
        private void AddSignatureProperties(SignedSignatureProperties signedSignatureProperties, SignedDataObjectProperties signedDataObjectProperties,
                                            UnsignedSignatureProperties unsignedSignatureProperties, string mimeType, X509Certificate2 certificado)
        {
            Cert cert;

            cert = new Cert();
            cert.IssuerSerial.X509IssuerName   = certificado.IssuerName.Name;
            cert.IssuerSerial.X509SerialNumber = CertUtil.HexToDecimal(certificado.SerialNumber);
            DigestUtil.SetCertDigest(_signCertificate.GetRawCertData(), _refsMethodUri, cert.CertDigest);
            signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);

            if (!string.IsNullOrEmpty(_policyId))
            {
                signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = false;
                signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyId.Identifier.IdentifierUri = _policyId;
            }

            if (!string.IsNullOrEmpty(_policyUri))
            {
                SigPolicyQualifier spq = new SigPolicyQualifier();
                spq.AnyXmlElement           = _document.CreateElement("SPURI", XadesSignedXml.XadesNamespaceUri);
                spq.AnyXmlElement.InnerText = _policyUri;

                signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyQualifiers.SigPolicyQualifierCollection.Add(spq);
            }

            if (!string.IsNullOrEmpty(_policyHash))
            {
                signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestMethod.Algorithm = SignedXml.XmlDsigSHA1Url;
                signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestValue            = Convert.FromBase64String(PolicyHash);
            }

            signedSignatureProperties.SigningTime = DateTime.Now;

            if (!string.IsNullOrEmpty(mimeType))
            {
                DataObjectFormat newDataObjectFormat = new DataObjectFormat();

                newDataObjectFormat.MimeType = mimeType;
                newDataObjectFormat.ObjectReferenceAttribute = "#" + _objectReference;

                signedDataObjectProperties.DataObjectFormatCollection.Add(newDataObjectFormat);
            }
        }
예제 #8
0
        private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, IEnumerable <string> ocspServers, IEnumerable <X509Crl> crlList, FirmaXades.Crypto.DigestMethod digestMethod, X509Certificate2[] extraCerts = null)
        {
            if (addCert)
            {
                if (CertificateChecked(cert, unsignedProperties))
                {
                    return;
                }
                string str   = Guid.NewGuid().ToString();
                Cert   cert2 = new Cert();
                cert2.IssuerSerial.X509IssuerName   = cert.IssuerName.Name;
                cert2.IssuerSerial.X509SerialNumber = cert.GetSerialNumberAsDecimalString();
                DigestUtil.SetCertDigest(cert.GetRawCertData(), digestMethod, cert2.CertDigest);
                cert2.URI = "#Cert" + str;
                unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(cert2);
                EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate();
                encapsulatedX509Certificate.Id      = "Cert" + str;
                encapsulatedX509Certificate.PkiData = cert.GetRawCertData();
                unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate);
            }
            X509ChainElementCollection chainElements = CertUtil.GetCertChain(cert, extraCerts).ChainElements;

            if (chainElements.Count > 1)
            {
                X509ChainElementEnumerator enumerator = chainElements.GetEnumerator();
                enumerator.MoveNext();
                enumerator.MoveNext();
                if (!ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate, crlList, digestMethod))
                {
                    X509Certificate2[] array = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate, ocspServers, digestMethod);
                    if (array != null)
                    {
                        X509Certificate2 x509Certificate = DetermineStartCert(new List <X509Certificate2>(array));
                        if (x509Certificate.IssuerName.Name != enumerator.Current.Certificate.SubjectName.Name)
                        {
                            X509Chain certChain = CertUtil.GetCertChain(x509Certificate, array);
                            AddCertificate(certChain.ChainElements[1].Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, array);
                        }
                    }
                }
                AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, extraCerts);
            }
        }
예제 #9
0
 private bool ValidateCertificateByCRL(UnsignedProperties unsignedProperties, X509Certificate2 certificate, X509Certificate2 issuer, IEnumerable <X509Crl> crlList, FirmaXades.Crypto.DigestMethod digestMethod)
 {
     Org.BouncyCastle.X509.X509Certificate cert            = certificate.ToBouncyX509Certificate();
     Org.BouncyCastle.X509.X509Certificate x509Certificate = issuer.ToBouncyX509Certificate();
     foreach (X509Crl crl in crlList)
     {
         if (crl.IssuerDN.Equivalent(x509Certificate.SubjectDN) && crl.NextUpdate.Value > DateTime.Now)
         {
             if (crl.IsRevoked(cert))
             {
                 throw new Exception("Certificado revocado");
             }
             if (!ExistsCRL(unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection, issuer.Subject))
             {
                 string text   = "CRLValue-" + Guid.NewGuid().ToString();
                 CRLRef cRLRef = new CRLRef();
                 cRLRef.CRLIdentifier.UriAttribute = "#" + text;
                 cRLRef.CRLIdentifier.Issuer       = issuer.Subject;
                 cRLRef.CRLIdentifier.IssueTime    = crl.ThisUpdate.ToLocalTime();
                 long?cRLNumber = GetCRLNumber(crl);
                 if (cRLNumber.HasValue)
                 {
                     cRLRef.CRLIdentifier.Number = cRLNumber.Value;
                 }
                 byte[] encoded = crl.GetEncoded();
                 DigestUtil.SetCertDigest(encoded, digestMethod, cRLRef.CertDigest);
                 CRLValue cRLValue = new CRLValue();
                 cRLValue.PkiData = encoded;
                 cRLValue.Id      = text;
                 unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection.Add(cRLRef);
                 unsignedProperties.UnsignedSignatureProperties.RevocationValues.CRLValues.CRLValueCollection.Add(cRLValue);
             }
             return(true);
         }
     }
     return(false);
 }
        private void AddSignatureProperties(SignatureDocument sigDocument, SignedSignatureProperties signedSignatureProperties, SignedDataObjectProperties signedDataObjectProperties,
                                            UnsignedSignatureProperties unsignedSignatureProperties, SignatureParameters parameters)
        {
            Cert cert;

            cert = new Cert();
            cert.IssuerSerial.X509IssuerName   = parameters.Signer.Certificate.IssuerName.Name;
            cert.IssuerSerial.X509SerialNumber = parameters.Signer.Certificate.GetSerialNumberAsDecimalString();
            DigestUtil.SetCertDigest(parameters.Signer.Certificate.GetRawCertData(), parameters.DigestMethod, cert.CertDigest);
            signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);

            if (parameters.SignaturePolicyInfo != null)
            {
                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyIdentifier))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = false;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyId.Identifier.IdentifierUri = parameters.SignaturePolicyInfo.PolicyIdentifier;
                }

                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyUri))
                {
                    SigPolicyQualifier spq = new SigPolicyQualifier();
                    spq.AnyXmlElement           = sigDocument.Document.CreateElement(XadesSignedXml.XmlXadesPrefix, "SPURI", XadesSignedXml.XadesNamespaceUri);
                    spq.AnyXmlElement.InnerText = parameters.SignaturePolicyInfo.PolicyUri;

                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyQualifiers.SigPolicyQualifierCollection.Add(spq);
                }

                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyHash))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestMethod.Algorithm = parameters.SignaturePolicyInfo.PolicyDigestAlgorithm.URI;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestValue            = Convert.FromBase64String(parameters.SignaturePolicyInfo.PolicyHash);
                }
            }

            signedSignatureProperties.SigningTime = parameters.SigningDate.HasValue ? parameters.SigningDate.Value : DateTime.Now;

            if (_dataFormat != null)
            {
                DataObjectFormat newDataObjectFormat = new DataObjectFormat();

                newDataObjectFormat.MimeType    = _dataFormat.MimeType;
                newDataObjectFormat.Encoding    = _dataFormat.Encoding;
                newDataObjectFormat.Description = _dataFormat.Description;
                newDataObjectFormat.ObjectReferenceAttribute = "#" + _refContent.Id;

                if (_dataFormat.ObjectIdentifier != null)
                {
                    newDataObjectFormat.ObjectIdentifier.Identifier.IdentifierUri = _dataFormat.ObjectIdentifier.Identifier.IdentifierUri;
                }

                signedDataObjectProperties.DataObjectFormatCollection.Add(newDataObjectFormat);
            }

            if (parameters.SignerRole != null &&
                (parameters.SignerRole.CertifiedRoles.Count > 0 || parameters.SignerRole.ClaimedRoles.Count > 0))
            {
                signedSignatureProperties.SignerRole = new Microsoft.Xades.SignerRole();

                foreach (X509Certificate certifiedRole in parameters.SignerRole.CertifiedRoles)
                {
                    signedSignatureProperties.SignerRole.CertifiedRoles.CertifiedRoleCollection.Add(new CertifiedRole()
                    {
                        PkiData = certifiedRole.GetRawCertData()
                    });
                }

                foreach (string claimedRole in parameters.SignerRole.ClaimedRoles)
                {
                    signedSignatureProperties.SignerRole.ClaimedRoles.ClaimedRoleCollection.Add(new ClaimedRole()
                    {
                        InnerText = claimedRole
                    });
                }
            }

            foreach (SignatureCommitment signatureCommitment in parameters.SignatureCommitments)
            {
                CommitmentTypeIndication cti = new CommitmentTypeIndication();
                cti.CommitmentTypeId.Identifier.IdentifierUri = signatureCommitment.CommitmentType.URI;
                cti.AllSignedDataObjects = true;

                foreach (XmlElement signatureCommitmentQualifier in signatureCommitment.CommitmentTypeQualifiers)
                {
                    CommitmentTypeQualifier ctq = new CommitmentTypeQualifier();
                    ctq.AnyXmlElement = signatureCommitmentQualifier;

                    cti.CommitmentTypeQualifiers.CommitmentTypeQualifierCollection.Add(ctq);
                }

                signedDataObjectProperties.CommitmentTypeIndicationCollection.Add(cti);
            }

            if (parameters.SignatureProductionPlace != null)
            {
                signedSignatureProperties.SignatureProductionPlace.City            = parameters.SignatureProductionPlace.City;
                signedSignatureProperties.SignatureProductionPlace.StateOrProvince = parameters.SignatureProductionPlace.StateOrProvince;
                signedSignatureProperties.SignatureProductionPlace.PostalCode      = parameters.SignatureProductionPlace.PostalCode;
                signedSignatureProperties.SignatureProductionPlace.CountryName     = parameters.SignatureProductionPlace.CountryName;
            }
        }
        private X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer,
                                                             IEnumerable <OcspServer> ocspServers, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl)
        {
            bool byKey = false;
            List <OcspServer> finalOcspServers = new List <OcspServer>();

            Org.BouncyCastle.X509.X509Certificate clientCert = client.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate issuerCert = issuer.ToBouncyX509Certificate();

            OcspClient ocsp = new OcspClient();

            if (addCertificateOcspUrl)
            {
                string certOcspUrl = ocsp.GetAuthorityInformationAccessOcspUrl(issuerCert);

                if (!string.IsNullOrEmpty(certOcspUrl))
                {
                    finalOcspServers.Add(new OcspServer(certOcspUrl));
                }
            }

            foreach (var ocspServer in ocspServers)
            {
                finalOcspServers.Add(ocspServer);
            }

            foreach (var ocspServer in finalOcspServers)
            {
                byte[] resp = ocsp.QueryBinary(clientCert, issuerCert, ocspServer.Url, ocspServer.RequestorName,
                                               ocspServer.SignCertificate);

                FirmaXadesNet.Clients.CertificateStatus status = ocsp.ProcessOcspResponse(resp);

                if (status == FirmaXadesNet.Clients.CertificateStatus.Revoked)
                {
                    throw new Exception("Certificado revocado");
                }
                else if (status == FirmaXadesNet.Clients.CertificateStatus.Good)
                {
                    Org.BouncyCastle.Ocsp.OcspResp r = new OcspResp(resp);
                    byte[]        rEncoded           = r.GetEncoded();
                    BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();

                    string guidOcsp = Guid.NewGuid().ToString();

                    OCSPRef ocspRef = new OCSPRef();
                    ocspRef.OCSPIdentifier.UriAttribute = "#OcspValue" + guidOcsp;
                    DigestUtil.SetCertDigest(rEncoded, digestMethod, ocspRef.CertDigest);

                    ResponderID rpId = or.ResponderId.ToAsn1Object();
                    ocspRef.OCSPIdentifier.ResponderID = GetResponderName(rpId, ref byKey);
                    ocspRef.OCSPIdentifier.ByKey       = byKey;

                    ocspRef.OCSPIdentifier.ProducedAt = or.ProducedAt.ToLocalTime();
                    unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.OCSPRefs.OCSPRefCollection.Add(ocspRef);

                    OCSPValue ocspValue = new OCSPValue();
                    ocspValue.PkiData = rEncoded;
                    ocspValue.Id      = "OcspValue" + guidOcsp;
                    unsignedProperties.UnsignedSignatureProperties.RevocationValues.OCSPValues.OCSPValueCollection.Add(ocspValue);

                    return((from cert in or.GetCerts()
                            select new X509Certificate2(cert.GetEncoded())).ToArray());
                }
            }

            throw new Exception("El certificado no ha podido ser validado");
        }