Example usage for org.bouncycastle.cms SignerInformation getDigestAlgorithmID

List of usage examples for org.bouncycastle.cms SignerInformation getDigestAlgorithmID

Introduction

In this page you can find the example usage for org.bouncycastle.cms SignerInformation getDigestAlgorithmID.

Prototype

public AlgorithmIdentifier getDigestAlgorithmID() 

Source Link

Usage

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_1_0.java

License:Open Source License

@Override
public void validate(byte[] content, byte[] contentSigned) {

    if (contentSigned == null || contentSigned.length == 0) {
        throw new SignaturePolicyException("Content signed is null");
    }//from  w ww  .j a v a  2  s .co m

    X509Certificate certificate = null;
    PublicKey publicKey = null;

    /*
     * Validando a integridade do arquivo
     */
    CMSSignedData signedData = null;
    try {
        if (content == null) {
            signedData = new CMSSignedData(contentSigned);
        } else {
            signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned);
        }
    } catch (CMSException exception) {
        throw new SignerException("Invalid bytes for a package PKCS7", exception);
    }

    /*
     * Validando as informaes da assinatura
     */
    SignerInformationStore signerInformationStore = signedData.getSignerInfos();
    SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator()
            .next();

    /*
     * Retirando o Certificado Digital e a chave Pblica da assinatura
     */
    try {
        CertStore certs;
        try {
            Security.addProvider(new BouncyCastleProvider());
            certs = signedData.getCertificatesAndCRLs("Collection", "BC");
            Collection<? extends Certificate> collCertificados = certs
                    .getCertificates(signerInformation.getSID());
            if (!collCertificados.isEmpty()) {
                certificate = (X509Certificate) collCertificados.iterator().next();
                publicKey = certificate.getPublicKey();
            }
        } catch (NoSuchAlgorithmException exception) {
            throw new SignerException(exception);
        } catch (NoSuchProviderException exception) {
            throw new SignerException(exception);
        } catch (CMSException exception) {
            throw new SignerException(exception);
        } catch (CertStoreException exception) {
            throw new SignerException(exception);
        }
    } catch (SignerException exception) {
        throw new SignerException(
                "Error on get information about certificates and public keys from a package PKCS7", exception);
    }

    /*
     * Validando os atributos assinados
     */
    AttributeTable signedAttributesTable = signerInformation.getSignedAttributes();

    /*
     * Validando o atributo ContentType
     */
    org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable
            .get(CMSAttributes.contentType);
    if (attributeContentType == null) {
        throw new SignerException("Package PKCS7 without attribute ContentType");
    }

    if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
        throw new SignerException("ContentType isn't a DATA type");
    }

    /*
     * Com o atributo ContentType vlido, extrair o contedo assinado, caso
     * possua o contedo atached
     */
    try {
        CMSProcessable contentProcessable = signedData.getSignedContent();
        if (contentProcessable != null) {
            content = (byte[]) contentProcessable.getContent();
        }
    } catch (Exception exception) {
        throw new SignerException(exception);
    }

    /*
     * Validando o atributo MessageDigest
     */
    org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable
            .get(CMSAttributes.messageDigest);
    if (attributeMessageDigest == null) {
        throw new SignerException("Package PKCS7 without attribute MessageDigest");
    }
    Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject();
    ASN1OctetString octeto = ASN1OctetString.getInstance(der);
    byte[] hashContentSigned = octeto.getOctets();

    String algorithm = SignerAlgorithmEnum
            .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString())
            .getAlgorithmHash();
    if (!algorithm.equals(DigestAlgorithmEnum.SHA_1.getAlgorithm())) {
        throw new SignerException("Algoritmo de resumo invlido para esta poltica");
    }

    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_1.getAlgorithm());
    byte[] hashContent = digest.digest(content);
    if (!MessageDigest.isEqual(hashContentSigned, hashContent)) {
        throw new SignerException("Hash not equal");
    }

    try {
        signerInformation.verify(publicKey, "BC");
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e);
    } catch (NoSuchProviderException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException("Invalid signature", e);
    }

    // Valida a cadeia de certificao de um arquivo assinado
    //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_1_0, CertPathEncoding.PKCS7);

    Date dataSigner = null;
    try {
        org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable
                .get(CMSAttributes.signingTime);
        ASN1Set valorDateSigner = attributeSigningTime.getAttrValues();
        DERSet derSet = (DERSet) valorDateSigner.getDERObject();
        DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0);
        dataSigner = time.getAdjustedDate();
    } catch (ParseException ex) {
        throw new SignerException("SigningTime error", ex);
    }

    //Para a verso 1.0, o perodo para assinatura desta PA  de 31/10/2008 a 31/12/2014.
    //        Calendar calendar = GregorianCalendar.getInstance();
    //        calendar.set(2008, Calendar.OCTOBER, 31, 0, 0, 0);
    //        Date firstDate = calendar.getTime();
    //
    //        calendar.set(2014, Calendar.DECEMBER, 31, 23, 59, 59);
    //        Date lastDate = calendar.getTime();
    //
    //        if (dataSigner != null) {
    //            if (dataSigner.before(firstDate)) {
    //                throw new SignerException("Invalid signing time. Not valid before 10/31/2008");
    //            }
    //            if (dataSigner.after(lastDate)) {
    //                throw new SignerException("Invalid signing time. Not valid after 12/31/2014");
    //            }
    //        } else {
    //            throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null");
    //        }
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_1_1.java

License:Open Source License

@Override
public void validate(byte[] content, byte[] contentSigned) {

    if (contentSigned == null || contentSigned.length == 0) {
        throw new SignaturePolicyException("Content signed is null");
    }/*w  w w.ja  va2s .c om*/

    X509Certificate certificate = null;
    PublicKey publicKey = null;

    // Validando a integridade do arquivo
    CMSSignedData signedData = null;
    try {
        if (content == null) {
            signedData = new CMSSignedData(contentSigned);
        } else {
            signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned);
        }
    } catch (CMSException exception) {
        throw new SignerException("Invalid bytes for a package PKCS7", exception);
    }

    // Validando as informaes da assinatura
    SignerInformationStore signerInformationStore = signedData.getSignerInfos();
    SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator()
            .next();

    // Retirando o Certificado Digital e a chave Pblica da assinatura
    try {
        CertStore certs;
        try {
            Security.addProvider(new BouncyCastleProvider());
            certs = signedData.getCertificatesAndCRLs("Collection", "BC");
            Collection<? extends Certificate> collCertificados = certs
                    .getCertificates(signerInformation.getSID());
            if (!collCertificados.isEmpty()) {
                certificate = (X509Certificate) collCertificados.iterator().next();
                publicKey = certificate.getPublicKey();
            }
        } catch (NoSuchAlgorithmException exception) {
            throw new SignerException(exception);
        } catch (NoSuchProviderException exception) {
            throw new SignerException(exception);
        } catch (CMSException exception) {
            throw new SignerException(exception);
        } catch (CertStoreException exception) {
            throw new SignerException(exception);
        }
    } catch (SignerException exception) {
        throw new SignerException(
                "Error on get information about certificates and public keys from a package PKCS7", exception);
    }

    // Validando os atributos assinados
    AttributeTable signedAttributesTable = signerInformation.getSignedAttributes();

    // Validando o atributo ContentType
    org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable
            .get(CMSAttributes.contentType);
    if (attributeContentType == null) {
        throw new SignerException("Package PKCS7 without attribute ContentType");
    }

    if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
        throw new SignerException("ContentType isn't a DATA type");
    }

    // Com o atributo ContentType vlido, extrair o contedo assinado, caso
    // possua o contedo atached
    try {
        CMSProcessable contentProcessable = signedData.getSignedContent();
        if (contentProcessable != null) {
            content = (byte[]) contentProcessable.getContent();
        }
    } catch (Exception exception) {
        throw new SignerException(exception);
    }

    // Validando o atributo MessageDigest
    org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable
            .get(CMSAttributes.messageDigest);
    if (attributeMessageDigest == null) {
        throw new SignerException("Package PKCS7 without attribute MessageDigest");
    }
    Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject();
    ASN1OctetString octeto = ASN1OctetString.getInstance(der);
    byte[] hashContentSigned = octeto.getOctets();

    String algorithm = SignerAlgorithmEnum
            .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString())
            .getAlgorithmHash();
    if (!algorithm.equals(DigestAlgorithmEnum.SHA_1.getAlgorithm())
            && !algorithm.equals(DigestAlgorithmEnum.SHA_256.getAlgorithm())) {
        throw new SignerException("Algoritmo de resumo invlido para esta poltica");
    }

    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(algorithm);
    byte[] hashContent = digest.digest(content);
    if (!MessageDigest.isEqual(hashContentSigned, hashContent)) {
        throw new SignerException("Hash not equal");
    }

    try {
        signerInformation.verify(publicKey, "BC");
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e);
    } catch (NoSuchProviderException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException("Invalid signature", e);
    }

    // O atributo signingCertificate deve conter referncia apenas ao
    // certificado do signatrio.
    org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable
            .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.12"));
    if (signedSigningCertificate != null) {
        // Uso futuro, para processamento dos valores
        ASN1Set set = signedSigningCertificate.getAttrValues();
    } else {
        throw new SignerException("O Atributo signingCertificate no pode ser nulo.");
    }

    // Valida a cadeia de certificao de um arquivo assinado
    //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_1_1, CertPathEncoding.PKCS7);

    Date dataSigner = null;
    try {
        org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable
                .get(CMSAttributes.signingTime);
        ASN1Set valorDateSigner = attributeSigningTime.getAttrValues();
        DERSet derSet = (DERSet) valorDateSigner.getDERObject();
        DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0);
        dataSigner = time.getAdjustedDate();
    } catch (Throwable error) {
        throw new SignerException("SigningTime error", error);
    }

    //Para a verso 1.1, o perodo para assinatura desta PA  de 26/12/2011 a 29/02/2012.
    //        Calendar calendar = GregorianCalendar.getInstance();
    //        calendar.set(2011, Calendar.DECEMBER, 26, 0, 0, 0);
    //        Date firstDate = calendar.getTime();
    //
    //        calendar.set(2012, Calendar.FEBRUARY, 29, 23, 59, 59);
    //        Date lastDate = calendar.getTime();
    //
    //        if (dataSigner != null) {
    //            if (dataSigner.before(firstDate)) {
    //                throw new SignerException("Invalid signing time. Not valid before 12/26/2011");
    //            }
    //            if (dataSigner.after(lastDate)) {
    //                throw new SignerException("Invalid signing time. Not valid after 02/29/2012");
    //            }
    //        } else {
    //            throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null");
    //        }
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_2_0.java

License:Open Source License

@Override
public void validate(byte[] content, byte[] contentSigned) {
    if (contentSigned == null || contentSigned.length == 0) {
        throw new SignaturePolicyException("Content signed is null");
    }//www.  j av a2s .c o m

    X509Certificate certificate = null;
    PublicKey publicKey = null;

    // Validando a integridade do arquivo
    CMSSignedData signedData = null;
    try {
        if (content == null) {
            signedData = new CMSSignedData(contentSigned);
        } else {
            signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned);
        }
    } catch (CMSException exception) {
        throw new SignerException("Invalid bytes for a package PKCS7", exception);
    }

    // Validando as informaes da assinatura
    SignerInformationStore signerInformationStore = signedData.getSignerInfos();
    SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator()
            .next();

    // Retirando o Certificado Digital e a chave Pblica da assinatura
    try {
        CertStore certs;
        try {
            Security.addProvider(new BouncyCastleProvider());
            certs = signedData.getCertificatesAndCRLs("Collection", "BC");
            Collection<? extends Certificate> collCertificados = certs
                    .getCertificates(signerInformation.getSID());
            if (!collCertificados.isEmpty()) {
                certificate = (X509Certificate) collCertificados.iterator().next();
                publicKey = certificate.getPublicKey();
            }
        } catch (NoSuchAlgorithmException exception) {
            throw new SignerException(exception);
        } catch (NoSuchProviderException exception) {
            throw new SignerException(exception);
        } catch (CMSException exception) {
            throw new SignerException(exception);
        } catch (CertStoreException exception) {
            throw new SignerException(exception);
        }
    } catch (SignerException exception) {
        throw new SignerException(
                "Error on get information about certificates and public keys from a package PKCS7", exception);
    }

    // Validando os atributos assinados
    AttributeTable signedAttributesTable = signerInformation.getSignedAttributes();

    // Validando o atributo ContentType
    org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable
            .get(CMSAttributes.contentType);
    if (attributeContentType == null) {
        throw new SignerException("Package PKCS7 without attribute ContentType");
    }

    if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
        throw new SignerException("ContentType isn't a DATA type");
    }

    // Com o atributo ContentType vlido, extrair o contedo assinado, caso
    // possua o contedo atached
    try {
        CMSProcessable contentProcessable = signedData.getSignedContent();
        if (contentProcessable != null) {
            content = (byte[]) contentProcessable.getContent();
        }
    } catch (Exception exception) {
        throw new SignerException(exception);
    }

    // Validando o atributo MessageDigest
    org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable
            .get(CMSAttributes.messageDigest);
    if (attributeMessageDigest == null) {
        throw new SignerException("Package PKCS7 without attribute MessageDigest");
    }
    Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject();
    ASN1OctetString octeto = ASN1OctetString.getInstance(der);
    byte[] hashContentSigned = octeto.getOctets();

    String algorithm = SignerAlgorithmEnum
            .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString())
            .getAlgorithmHash();
    if (!algorithm.equals(DigestAlgorithmEnum.SHA_256.getAlgorithm())) {
        throw new SignerException("Algoritmo de resumo invlido para esta poltica");
    }
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_256.getAlgorithm());
    byte[] hashContent = digest.digest(content);
    if (!MessageDigest.isEqual(hashContentSigned, hashContent)) {
        throw new SignerException("Hash not equal");
    }

    try {
        signerInformation.verify(publicKey, "BC");
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e);
    } catch (NoSuchProviderException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException("Invalid signature", e);
    }

    // O atributo signingCertificate deve conter referncia apenas ao
    // certificado do signatrio.
    org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable
            .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.12"));
    if (signedSigningCertificate != null) {
        // Uso futuro, para processamento dos valores
        ASN1Set set = signedSigningCertificate.getAttrValues();
    } else {
        throw new SignerException("O Atributo signingCertificate no pode ser nulo.");
    }

    // Valida a cadeia de certificao de um arquivo assinado
    //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_2_0, CertPathEncoding.PKCS7);

    Date dataSigner = null;
    try {
        org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable
                .get(CMSAttributes.signingTime);
        ASN1Set valorDateSigner = attributeSigningTime.getAttrValues();
        DERSet derSet = (DERSet) valorDateSigner.getDERObject();
        DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0);
        dataSigner = time.getAdjustedDate();
    } catch (ParseException ex) {

    }

    //Para a verso 2.0, o perodo para assinatura desta PA  de 26/12/2011 a 21/06/2023.
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.set(2011, Calendar.DECEMBER, 26, 0, 0, 0);
    Date firstDate = calendar.getTime();

    calendar.set(2023, Calendar.JUNE, 21, 23, 59, 59);
    Date lastDate = calendar.getTime();

    if (dataSigner != null) {
        if (dataSigner.before(firstDate)) {
            throw new SignerException("Invalid signing time. Not valid before 12/26/2011");
        }
        if (dataSigner.after(lastDate)) {
            throw new SignerException("Invalid signing time. Not valid after 06/21/2023");
        }
    } else {
        throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null");
    }

}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_2_1.java

License:Open Source License

@Override
public void validate(byte[] content, byte[] contentSigned) {
    if (contentSigned == null || contentSigned.length == 0) {
        throw new SignaturePolicyException("Content signed is null");
    }/*from   ww  w. ja v  a  2  s .  c om*/

    X509Certificate certificate = null;
    PublicKey publicKey = null;

    // Validando a integridade do arquivo
    CMSSignedData signedData = null;
    try {
        if (content == null) {
            signedData = new CMSSignedData(contentSigned);
        } else {
            signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned);
        }
    } catch (CMSException exception) {
        throw new SignerException("Invalid bytes for a package PKCS7", exception);
    }

    // Validando as informaes da assinatura
    SignerInformationStore signerInformationStore = signedData.getSignerInfos();
    SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator()
            .next();

    // Retirando o Certificado Digital e a chave Pblica da assinatura
    try {
        CertStore certs;
        try {
            Security.addProvider(new BouncyCastleProvider());
            certs = signedData.getCertificatesAndCRLs("Collection", "BC");
            Collection<? extends Certificate> collCertificados = certs
                    .getCertificates(signerInformation.getSID());
            if (!collCertificados.isEmpty()) {
                certificate = (X509Certificate) collCertificados.iterator().next();
                publicKey = certificate.getPublicKey();
            }
        } catch (NoSuchAlgorithmException exception) {
            throw new SignerException(exception);
        } catch (NoSuchProviderException exception) {
            throw new SignerException(exception);
        } catch (CMSException exception) {
            throw new SignerException(exception);
        } catch (CertStoreException exception) {
            throw new SignerException(exception);
        }
    } catch (SignerException exception) {
        throw new SignerException(
                "Error on get information about certificates and public keys from a package PKCS7", exception);
    }

    // Validando os atributos assinados
    AttributeTable signedAttributesTable = signerInformation.getSignedAttributes();

    // Validando o atributo ContentType
    org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable
            .get(CMSAttributes.contentType);
    if (attributeContentType == null) {
        throw new SignerException("Package PKCS7 without attribute ContentType");
    }

    if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
        throw new SignerException("ContentType isn't a DATA type");
    }

    // Com o atributo ContentType vlido, extrair o contedo assinado, caso
    // possua o contedo atached
    try {
        CMSProcessable contentProcessable = signedData.getSignedContent();
        if (contentProcessable != null) {
            content = (byte[]) contentProcessable.getContent();
        }
    } catch (Exception exception) {
        throw new SignerException(exception);
    }

    // Validando o atributo MessageDigest
    org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable
            .get(CMSAttributes.messageDigest);
    if (attributeMessageDigest == null) {
        throw new SignerException("Package PKCS7 without attribute MessageDigest");
    }
    Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject();
    ASN1OctetString octeto = ASN1OctetString.getInstance(der);
    byte[] hashContentSigned = octeto.getOctets();

    String algorithm = SignerAlgorithmEnum
            .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString())
            .getAlgorithmHash();
    if (!algorithm.equals(DigestAlgorithmEnum.SHA_256.getAlgorithm())) {
        throw new SignerException("Algoritmo de resumo invlido para esta poltica");
    }
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_256.getAlgorithm());
    byte[] hashContent = digest.digest(content);
    if (!MessageDigest.isEqual(hashContentSigned, hashContent)) {
        throw new SignerException("Hash not equal");
    }

    try {
        signerInformation.verify(publicKey, "BC");
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e);
    } catch (NoSuchProviderException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException("Invalid signature", e);
    }

    // Valida a cadeia de certificao de um arquivo assinado
    //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_2_0, CertPathEncoding.PKCS7);

    Date dataSigner = null;
    try {
        org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable
                .get(CMSAttributes.signingTime);
        ASN1Set valorDateSigner = attributeSigningTime.getAttrValues();
        DERSet derSet = (DERSet) valorDateSigner.getDERObject();
        DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0);
        dataSigner = time.getAdjustedDate();
    } catch (Throwable error) {

    }

    //Para a verso 2.1, o perodo para assinatura desta PA  de 06/03/2012 a 21/06/2023.
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.set(2012, Calendar.MARCH, 06, 0, 0, 0);
    Date firstDate = calendar.getTime();

    calendar.set(2023, Calendar.JUNE, 21, 23, 59, 59);
    Date lastDate = calendar.getTime();

    if (dataSigner != null) {
        if (dataSigner.before(firstDate)) {
            throw new SignerException("Invalid signing time. Not valid before 03/06/2012");
        }
        if (dataSigner.after(lastDate)) {
            throw new SignerException("Invalid signing time. Not valid after 06/21/2023");
        }
    } else {
        throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null");
    }

    // O atributo signingCertificate deve conter referncia apenas ao
    // certificado do signatrio.
    org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable
            .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.47"));
    if (signedSigningCertificate != null) {
        // Uso futuro, para processamento dos valores
        ASN1Set set = signedSigningCertificate.getAttrValues();
    } else {
        throw new SignerException("O Atributo signingCertificate no pode ser nulo.");
    }

}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_2_2.java

License:Open Source License

@Override
public void validate(byte[] content, byte[] contentSigned) {
    if (contentSigned == null || contentSigned.length == 0) {
        throw new SignaturePolicyException("Content signed is null");
    }/*from w  ww  .  j  a v  a 2  s  .  c om*/

    X509Certificate certificate = null;
    PublicKey publicKey = null;

    // Validando a integridade do arquivo
    CMSSignedData signedData = null;
    try {
        if (content == null) {
            signedData = new CMSSignedData(contentSigned);
        } else {
            signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned);
        }
    } catch (CMSException exception) {
        throw new SignerException("Invalid bytes for a package PKCS7", exception);
    }

    // Validando as informaes da assinatura
    SignerInformationStore signerInformationStore = signedData.getSignerInfos();
    SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator()
            .next();

    // Retirando o Certificado Digital e a chave Pblica da assinatura
    try {
        CertStore certs;
        try {
            Security.addProvider(new BouncyCastleProvider());
            certs = signedData.getCertificatesAndCRLs("Collection", "BC");
            Collection<? extends Certificate> collCertificados = certs
                    .getCertificates(signerInformation.getSID());
            if (!collCertificados.isEmpty()) {
                certificate = (X509Certificate) collCertificados.iterator().next();
                publicKey = certificate.getPublicKey();
            }
        } catch (NoSuchAlgorithmException exception) {
            throw new SignerException(exception);
        } catch (NoSuchProviderException exception) {
            throw new SignerException(exception);
        } catch (CMSException exception) {
            throw new SignerException(exception);
        } catch (CertStoreException exception) {
            throw new SignerException(exception);
        }
    } catch (SignerException exception) {
        throw new SignerException(
                "Error on get information about certificates and public keys from a package PKCS7", exception);
    }

    // Validando os atributos assinados
    AttributeTable signedAttributesTable = signerInformation.getSignedAttributes();

    // Validando o atributo ContentType
    org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable
            .get(CMSAttributes.contentType);
    if (attributeContentType == null) {
        throw new SignerException("Package PKCS7 without attribute ContentType");
    }

    if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
        throw new SignerException("ContentType isn't a DATA type");
    }

    // Com o atributo ContentType vlido, extrair o contedo assinado, caso
    // possua o contedo atached
    try {
        CMSProcessable contentProcessable = signedData.getSignedContent();
        if (contentProcessable != null) {
            content = (byte[]) contentProcessable.getContent();
        }
    } catch (Exception exception) {
        throw new SignerException(exception);
    }

    // Validando o atributo MessageDigest
    org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable
            .get(CMSAttributes.messageDigest);
    if (attributeMessageDigest == null) {
        throw new SignerException("Package PKCS7 without attribute MessageDigest");
    }
    Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject();
    ASN1OctetString octeto = ASN1OctetString.getInstance(der);
    byte[] hashContentSigned = octeto.getOctets();

    String algorithm = SignerAlgorithmEnum
            .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString())
            .getAlgorithmHash();
    if (!(DigestAlgorithmEnum.SHA_256.getAlgorithm().equalsIgnoreCase(algorithm)
            || DigestAlgorithmEnum.SHA_512.getAlgorithm().equalsIgnoreCase(algorithm))) {
        throw new SignerException("Algoritmo de resumo invlido para esta poltica");
    }
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(algorithm);
    byte[] hashContent = digest.digest(content);
    if (!MessageDigest.isEqual(hashContentSigned, hashContent)) {
        throw new SignerException("Hash not equal");
    }

    try {
        signerInformation.verify(publicKey, "BC");
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e);
    } catch (NoSuchProviderException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException("Invalid signature", e);
    }

    // Valida a cadeia de certificao de um arquivo assinado
    //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_2_0, CertPathEncoding.PKCS7);

    Date dataSigner = null;
    try {
        org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable
                .get(CMSAttributes.signingTime);
        ASN1Set valorDateSigner = attributeSigningTime.getAttrValues();
        DERSet derSet = (DERSet) valorDateSigner.getDERObject();
        DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0);
        dataSigner = time.getAdjustedDate();
    } catch (Throwable error) {

    }

    //Para a verso 2.2, o perodo para assinatura desta PA  de 06/03/2012 a 21/06/2023.
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.set(2012, Calendar.APRIL, 27, 0, 0, 0);
    Date firstDate = calendar.getTime();

    calendar.set(2029, Calendar.MARCH, 02, 23, 59, 59);
    Date lastDate = calendar.getTime();

    if (dataSigner != null) {
        if (dataSigner.before(firstDate)) {
            throw new SignerException("Invalid signing time. Not valid before 03/06/2012");
        }
        if (dataSigner.after(lastDate)) {
            throw new SignerException("Invalid signing time. Not valid after 06/21/2023");
        }
    } else {
        throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null");
    }

    // O atributo signingCertificate deve conter referncia apenas ao
    // certificado do signatrio.
    org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable
            .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.47"));
    if (signedSigningCertificate != null) {
        // Uso futuro, para processamento dos valores
        ASN1Set set = signedSigningCertificate.getAttrValues();
    } else {
        throw new SignerException("O Atributo signingCertificate no pode ser nulo.");
    }

}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

/**
 * Interpreta um dado do tipo otherName. Obs. O JDK 5.0 no tem classes que
 * lidem com um dado do tipo OtherName.  necessrio usar o BouncyCastle.
 * //from  w w  w.j a v  a 2s .  c  o m
 * @param encoded
 *            O dado em ASN.1.
 * @return Um par contendo o OID e o contedo.
 */
/*
 * @SuppressWarnings("unchecked") private static Pair<DERObjectIdentifier,
 * String> getOtherName(byte[] encoded) throws IOException { // O JDK 5.0
 * no tem classes que lidem com um dado do tipo OtherName. //  necessrio
 * usar o BouncyCastle. ASN1InputStream inps = new ASN1InputStream(encoded);
 * DERSequence seq = null; DERObjectIdentifier oid = null; String conteudo =
 * ""; seq = (DERSequence) inps.readObject(); inps.close(); Enumeration en =
 * seq.getObjects(); oid = (DERObjectIdentifier) en.nextElement(); DERObject
 * obj = ((ASN1TaggedObject) ((ASN1TaggedObject) en
 * .nextElement()).getObject()).getObject(); if (obj instanceof DERString) {
 * // Certificados antigos SERASA - // incorretos conteudo = ((DERString)
 * obj).getString(); } else if (obj instanceof DEROctetString) { //
 * Certificados corretos conteudo = new String(((DEROctetString)
 * obj).getOctets(), "ISO-8859-1"); } return new Pair<DERObjectIdentifier,
 * String>(oid, conteudo); }
 */
@SuppressWarnings("unchecked")
protected static Properties recuperaNomesAlternativos(final byte[] assinatura)
        throws InvalidKeyException, SecurityException, CRLException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException,
        ChainValidationException, IOException, CMSException, CertStoreException {

    final CMSSignedData signedData = new CMSSignedData(assinatura);

    //      CertStore certs = signedData.getCertificatesAndCRLs("Collection", "BC");
    Store certs = signedData.getCertificates();
    SignerInformationStore signers = signedData.getSignerInfos();
    Collection<SignerInformation> c = signers.getSigners();
    Iterator<SignerInformation> it = c.iterator();

    @SuppressWarnings("unused")
    String sCN = "";

    while (it.hasNext()) {
        SignerInformation signer = it.next();
        //         Collection certCollection = certs.getCertificates(signer.getSID());
        Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());

        @SuppressWarnings("unused")
        String ss = signer.getDigestAlgOID();
        @SuppressWarnings("unused")
        String sss = signer.getDigestAlgorithmID().getObjectId().getId();

        Iterator<X509CertificateHolder> certIt = certCollection.iterator();
        X509CertificateHolder certHolder = certIt.next();
        X509Certificate cert = AssinaturaDigital.getX509Certificate(certHolder);

        /*
         *  *** cdigo comentado movido para
         * Certificado.recuperarPropriedadesNomesAlteranativos(cert)*****
         * ATENO: Cdigo sempre retorna na primeira iterao do for ?!!***
         * (LAGS) Properties props = new Properties(); for (List<?>
         * subjectAlternativeName : cert .getSubjectAlternativeNames()) {
         * String email; Pair<DERObjectIdentifier, String> otherName;
         * 
         * @SuppressWarnings("unused") int pos;
         * 
         * // O primeiro elemento  um Integer com o valor 0 = otherName, 1
         * // = // rfc822name etc. // O segundo valor  um byte array ou uma
         * String. Veja o javadoc // de // getSubjectAlternativeNames.
         * switch (((Number) subjectAlternativeName.get(0)).intValue()) {
         * case 0: // OtherName - contm CPF, CNPJ etc. // o OID fica em
         * otherName.first otherName = getOtherName((byte[])
         * subjectAlternativeName .get(1));
         * props.put(otherName.first.getId(), otherName.second); break; case
         * 1: // rfc822Name - usado para email email = (String)
         * subjectAlternativeName.get(1); props.put("email", email); break;
         * default: break; } } return props;
         */
        return CertificadoUtil.recuperarPropriedadesNomesAlteranativos(cert);
    }
    return null;
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
public static String validarAssinaturaPKCS7(final byte[] digest, final String digestAlgorithm,
        final byte[] assinatura, Date dtAssinatura, boolean verificarLCRs)
        throws InvalidKeyException, SecurityException, CRLException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException,
        ChainValidationException, IOException, Exception {

    Map<String, byte[]> map = new HashMap<String, byte[]>();
    map.put(digestAlgorithm, digest);// w w w.  j  a  va2  s .c  o  m
    final CMSSignedData signedData = new CMSSignedData(map, assinatura);

    Store certs = signedData.getCertificates();
    SignerInformationStore signers = signedData.getSignerInfos();
    Collection<SignerInformation> c = signers.getSigners();
    Iterator<SignerInformation> it = c.iterator();

    String sCN = "";

    while (it.hasNext()) {
        SignerInformation signer = it.next();
        Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());

        @SuppressWarnings("unused")
        String ss = signer.getDigestAlgOID();
        @SuppressWarnings("unused")
        String sss = signer.getDigestAlgorithmID().getObjectId().getId();

        Iterator<X509CertificateHolder> certIt = certCollection.iterator();
        X509CertificateHolder certHolder = certIt.next();
        X509Certificate cert = AssinaturaDigital.getX509Certificate(certHolder);

        if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder)))
            throw new Exception("Assinatura invlida!");

        X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certCollection);

        final X509ChainValidator cadeia = new X509ChainValidator(cadeiaTotal,
                /* trustedAnchors */new HashSet(FachadaDeCertificadosAC.getTrustAnchors()), null);
        cadeia.checkCRL(verificarLCRs);
        cadeia.validateChain(dtAssinatura);

        String s2 = cert.getSubjectDN().getName();
        s2 = obterNomeExibicao(s2);
        if (sCN.length() != 0)
            sCN += ", ";
        sCN += s2;
    }

    return sCN.length() == 0 ? null : sCN;
}

From source file:net.jsign.pe.PEFile.java

License:Apache License

/**
 * Print detailed informations about the PE file.
 *//*from   w  ww.  jav  a2s .  co m*/
public void printInfo(PrintWriter out) {
    out.println("PE File");
    out.println("  Name:          " + raf.getName());
    out.println("  Size:          " + raf.length());
    out.println("  Last Modified: " + new Date(raf.lastModified()));
    out.println();

    out.println("PE Header");
    out.println("  Machine:                    " + getMachineType());
    out.println("  Number of sections:         " + getNumberOfSections());
    out.println("  Timestamp:                  " + getTimeDateStamp());
    out.println("  Pointer to symbol table:    0x" + Long.toHexString(getPointerToSymbolTable()));
    out.println("  Number of symbols:          " + getNumberOfSymbols());
    out.println("  Size of optional header:    " + getSizeOfOptionalHeader());
    out.println("  Characteristics:            0x" + Long.toBinaryString(getCharacteristics()));
    out.println();

    out.println("Optional Header");
    PEFormat format = getFormat();
    out.println(
            "  PE Format:                  0x" + Integer.toHexString(format.value) + " (" + format.label + ")");
    out.println("  Linker version:             " + getMajorLinkerVersion() + "." + getMinorLinkerVersion());
    out.println("  Size of code:               " + getSizeOfCode());
    out.println("  Size of initialized data:   " + getSizeOfInitializedData());
    out.println("  Size of uninitialized data: " + getSizeOfUninitializedData());
    out.println("  Address of entry point:     0x" + Long.toHexString(getAddressOfEntryPoint()));
    out.println("  Base of code:               0x" + Long.toHexString(getBaseOfCode()));
    if (PEFormat.PE32.equals(getFormat())) {
        out.println("  Base of data:               0x" + Long.toHexString(getBaseOfData()));
    }
    out.println("  Image base:                 0x" + Long.toHexString(getImageBase()));
    out.println("  Section alignment:          " + getSectionAlignment());
    out.println("  File alignment:             " + getFileAlignment());
    out.println("  Operating system version:   " + getMajorOperatingSystemVersion() + "."
            + getMinorOperatingSystemVersion());
    out.println("  Image version:              " + getMajorImageVersion() + "." + getMinorImageVersion());
    out.println(
            "  Subsystem version:          " + getMajorSubsystemVersion() + "." + getMinorSubsystemVersion());
    out.println("  Size of image:              " + getSizeOfImage());
    out.println("  Size of headers:            " + getSizeOfHeaders());
    out.println("  Checksum:                   0x" + Long.toHexString(getCheckSum()));
    out.println("  Checksum (computed):        0x" + Long.toHexString(computeChecksum()));
    out.println("  Subsystem:                  " + getSubsystem());
    out.println("  DLL characteristics:        0x" + Long.toBinaryString(getDllCharacteristics()));
    out.println("  Size of stack reserve:      " + getSizeOfStackReserve());
    out.println("  Size of stack commit:       " + getSizeOfStackCommit());
    out.println("  Size of heap reserve:       " + getSizeOfHeapReserve());
    out.println("  Size of heap commit:        " + getSizeOfHeapCommit());
    out.println("  Number of RVA and sizes:    " + getNumberOfRvaAndSizes());
    out.println();

    out.println("Data Directory");
    for (DataDirectoryType type : DataDirectoryType.values()) {
        DataDirectory entry = getDataDirectory(type);
        if (entry != null && entry.getVirtualAddress() != 0) {
            out.printf("  %-30s 0x%08x %8d bytes\n", type, entry.getVirtualAddress(), entry.getSize());
        }
    }
    out.println();

    int sectionTableOffset = getDataDirectoryOffset() + 8 * getNumberOfRvaAndSizes();
    out.println("Sections");
    out.println("      Name     Virtual Size  Virtual Address  Raw Data Size  Raw Data Ptr  Characteristics");
    for (int i = 0; i < getNumberOfSections(); i++) {
        Section section = new Section(this, sectionTableOffset + 40 * i);
        out.printf("  #%d  %-8s     %8d       0x%08x       %8d    0x%08x  %s\n", i + 1, section.getName(),
                section.getVirtualSize(), section.getVirtualAddress(), section.getSizeOfRawData(),
                section.getPointerToRawData(), section.getCharacteristics());
    }
    out.println();

    List<CMSSignedData> signatures = getSignatures();
    if (!signatures.isEmpty()) {
        out.println("Signatures");
        for (CMSSignedData signedData : signatures) {
            SignerInformation signerInformation = signedData.getSignerInfos().getSigners().iterator().next();
            X509CertificateHolder certificate = (X509CertificateHolder) signedData.getCertificates()
                    .getMatches(signerInformation.getSID()).iterator().next();

            String commonName = certificate.getSubject().getRDNs(X509ObjectIdentifiers.commonName)[0].getFirst()
                    .getValue().toString();

            AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
            boolean timestamped = unsignedAttributes != null
                    && (unsignedAttributes.get(PKCSObjectIdentifiers.pkcs_9_at_counterSignature) != null
                            || unsignedAttributes.get(AuthenticodeObjectIdentifiers.SPC_RFC3161_OBJID) != null);
            DigestAlgorithm algorithm = DigestAlgorithm
                    .of(signerInformation.getDigestAlgorithmID().getAlgorithm());
            out.println("  " + commonName + "  " + (algorithm != null ? "[" + algorithm.id + "]  " : "")
                    + (timestamped ? "(timestamped)" : ""));
        }
    }
}

From source file:org.signserver.module.cmssigner.CMSSignerTest.java

License:Open Source License

private void helperBasicCMSSign(final int workerId, final String sigAlg, final String expectedDigAlgOID,
        final String expectedEncAlgOID, final String includedCertificateLevelsProperty,
        final int expectedIncludedCertificateLevels) throws Exception {
    final int reqid = 37;

    final String testDocument = "Something to sign...123";

    final GenericSignRequest signRequest = new GenericSignRequest(reqid, testDocument.getBytes());

    // override signature algorithm if set
    if (sigAlg != null) {
        workerSession.setWorkerProperty(workerId, CMSSigner.SIGNATUREALGORITHM_PROPERTY, sigAlg);
    } else {/*from   ww  w .  ja  v  a  2 s  . c  o  m*/
        workerSession.removeWorkerProperty(workerId, CMSSigner.SIGNATUREALGORITHM_PROPERTY);
    }

    if (includedCertificateLevelsProperty != null) {
        workerSession.setWorkerProperty(workerId, WorkerConfig.PROPERTY_INCLUDE_CERTIFICATE_LEVELS,
                includedCertificateLevelsProperty);
    } else {
        workerSession.removeWorkerProperty(workerId, WorkerConfig.PROPERTY_INCLUDE_CERTIFICATE_LEVELS);
    }

    workerSession.reloadConfiguration(workerId);

    final GenericSignResponse res = (GenericSignResponse) workerSession.process(workerId, signRequest,
            new RequestContext());
    final byte[] data = res.getProcessedData();

    // Answer to right question
    assertSame("Request ID", reqid, res.getRequestID());

    // Output for manual inspection
    final FileOutputStream fos = new FileOutputStream(
            new File(getSignServerHome(), "tmp" + File.separator + "signedcms_" + sigAlg + ".p7s"));
    fos.write((byte[]) data);
    fos.close();

    // Check certificate returned
    final Certificate signercert = res.getSignerCertificate();
    assertNotNull("Signer certificate", signercert);

    // Check that the signed data contains the document (i.e. not detached)
    final CMSSignedData signedData = new CMSSignedData(data);
    final byte[] content = (byte[]) signedData.getSignedContent().getContent();
    assertEquals("Signed document", testDocument, new String(content));

    // Get signers
    final Collection signers = signedData.getSignerInfos().getSigners();
    final SignerInformation signer = (SignerInformation) signers.iterator().next();

    // Verify using the signer's certificate
    assertTrue("Verification using signer certificate", signer.verify(signercert.getPublicKey(), "BC"));

    // Check that the signer's certificate is included
    CertStore certs = signedData.getCertificatesAndCRLs("Collection", "BC");
    X509Principal issuer = new X509Principal(signer.getSID().getIssuer());
    CertSelector cs = new AttributeCertificateHolder(issuer, signer.getSID().getSerialNumber());
    Collection<? extends Certificate> signerCerts = certs.getCertificates(cs);
    assertEquals("Certificate included", expectedIncludedCertificateLevels, signerCerts.size());
    if (!signerCerts.isEmpty()) {
        assertEquals(signercert, signerCerts.iterator().next());
    }

    // check the signature algorithm
    assertEquals("Digest algorithm", expectedDigAlgOID, signer.getDigestAlgorithmID().getAlgorithm().getId());
    assertEquals("Encryption algorithm", expectedEncAlgOID, signer.getEncryptionAlgOID());
}

From source file:org.votingsystem.signature.dnie.DNIePDFContentSigner.java

License:Open Source License

public CMSSignedData getCMSSignedData(String eContentType, CMSProcessable content, boolean encapsulate,
        Provider sigProvider, boolean addDefaultAttributes, List signerInfs) throws Exception {
    // TODO if (signerInfs.isEmpty()){
    //            /* RFC 3852 5.2
    //             * "In the degenerate case where there are no signers, the
    //             * EncapsulatedContentInfo value being "signed" is irrelevant.  In this
    //             * case, the content type within the EncapsulatedContentInfo value being
    //             * "signed" MUST be id-data (as defined in section 4), and the content
    //             * field of the EncapsulatedContentInfo value MUST be omitted."
    //             *//*www.  j a  va2s. co m*/
    //            if (encapsulate) {
    //                throw new IllegalArgumentException("no signers, encapsulate must be false");
    //            } if (!DATA.equals(eContentType)) {
    //                throw new IllegalArgumentException("no signers, eContentType must be id-data");
    //            }
    //        }
    //        if (!DATA.equals(eContentType)) {
    //            /* RFC 3852 5.3
    //             * [The 'signedAttrs']...
    //             * field is optional, but it MUST be present if the content type of
    //             * the EncapsulatedContentInfo value being signed is not id-data.
    //             */
    //            // TODO signedAttrs must be present for all signers
    //        }
    ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    digests.clear(); // clear the current preserved digest state
    Iterator it = _signers.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        digestAlgs.add(CMSUtils.fixAlgID(signer.getDigestAlgorithmID()));
        signerInfos.add(signer.toSignerInfo());
    }
    boolean isCounterSignature = (eContentType == null);
    ASN1ObjectIdentifier contentTypeOID = isCounterSignature ? CMSObjectIdentifiers.data
            : new ASN1ObjectIdentifier(eContentType);
    it = signerInfs.iterator();
    while (it.hasNext()) {
        SignerInf signer = (SignerInf) it.next();
        log.info("signer.signerIdentifier: " + signer.signerIdentifier.toASN1Object().toString());
        digestAlgs.add(signer.getDigestAlgorithmID());
        signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, null, addDefaultAttributes,
                isCounterSignature));
    }
    ASN1Set certificates = null;
    if (!certs.isEmpty())
        certificates = CMSUtils.createBerSetFromList(certs);
    ASN1Set certrevlist = null;
    if (!crls.isEmpty())
        certrevlist = CMSUtils.createBerSetFromList(crls);
    ASN1OctetString octs = null;
    if (encapsulate && content != null) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        content.write(bOut);
        octs = new BERConstructedOctetString(bOut.toByteArray());
    }
    ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);
    SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist,
            new DERSet(signerInfos));
    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
    return new CMSSignedData(content, contentInfo);
}