Example usage for org.bouncycastle.cms SignerInformation getSignedAttributes

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

Introduction

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

Prototype

public AttributeTable getSignedAttributes() 

Source Link

Document

return a table of the signed attributes - indexed by the OID of the attribute.

Usage

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

License:Open Source License

/**
 * A validao se basea apenas em assinaturas com um assinante apenas.
 * Valida apenas com o contedo do tipo DATA: OID ContentType
 * 1.2.840.113549.1.9.3 = OID Data 1.2.840.113549.1.7.1
 *
 * @param content/* w w w .  jav  a 2 s.  c om*/
 * @param signed
 * @return
 * @params content Necessrio informar apenas se o pacote PKCS7 NO for do
 * tipo ATTACHED. Caso seja do tipo attached, este parmetro ser
 * substituido pelo contedo do pacote PKCS7.
 * @params signed Valor em bytes do pacote PKCS7, como por exemplo o
 * contedo de um arquivo ".p7s". No  a assinatura pura como no caso do
 * PKCS1. TODO: Implementar validao de co-assinaturas
 */
@Override
public boolean check(byte[] content, byte[] signed) {

    CMSSignedData signedData = null;
    PublicKey publicKey = null;

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

    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 ex) {
        throw new SignerException(
                "Error on get information about certificates and public keys from a package PKCS7", ex);
    }

    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);
    }

    AttributeTable signedAttributes = signerInformation.getSignedAttributes();

    if (signedAttributes == null) {
        throw new SignerException("Package PKCS7 without signed attributes");
    }

    // Validar a poltica
    org.bouncycastle.asn1.cms.Attribute signaturePolicyIdentifierAttribute = signedAttributes
            .get(new DERObjectIdentifier((new SignaturePolicyIdentifier()).getOID()));
    if (signaturePolicyIdentifierAttribute != null) {
        ASN1Set valueAttribute = signaturePolicyIdentifierAttribute.getAttrValues();
        for (Enumeration<DERSequence> iterator = valueAttribute.getObjects(); iterator.hasMoreElements();) {
            DERSequence sequence = iterator.nextElement();
            DERObjectIdentifier policyIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0);
            String policyOID = policyIdentifier.getId();
            SignaturePolicy policy = SignaturePolicyFactory.getInstance().factory(policyOID);
            if (policy != null) {
                policy.validate(content, signed);
            } else {
                LOGGER.log(Level.WARNING, "N\u00e3o existe validador para a pol\u00edtica {0}", policyOID);
            }
        }
    } else {
        throw new SignerException("ICP-Brasil invalid format. There is not policy signature.");
    }
    return true;
}

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  www . ja v a  2s  . 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");
    }//from  ww w  . j  ava2 s . 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_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");
    }/*from   www  .  j  a 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_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  w w w . j ava2  s.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);
    }

    // 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  .  ja v a2 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:com.yacme.ext.oxsit.cust_it.security.crl.RootsVerifier.java

License:Open Source License

private byte[] getFingerprint() {

    byte[] fingerprint = null;
    String sDispDate = "";

    CertStore certs = null;/* w w  w .j  a  v  a  2s . c o m*/
    CMSSignedData CNIPA_CMS = null;
    try {
        CNIPA_CMS = getCNIPA_CMS();

        Provider p = new org.bouncycastle.jce.provider.BouncyCastleProvider();
        if (Security.getProvider(p.getName()) == null)
            Security.addProvider(p);

        try {
            certs = CNIPA_CMS.getCertificatesAndCRLs("Collection", "BC");
        } catch (CMSException ex2) {
            m_aLogger.severe("getFingerprint", "Errore nel CMS delle RootCA", ex2);
        } catch (NoSuchProviderException ex2) {
            m_aLogger.severe("getFingerprint", "Non esiste il provider del servizio", ex2);
        } catch (NoSuchAlgorithmException ex2) {
            m_aLogger.severe("getFingerprint", "Errore nell'algoritmo", ex2);
        }

        if (certs == null)
            m_aLogger.severe("getFingerprint", "No certs for CNIPA signature!");
        else {
            SignerInformationStore signers = CNIPA_CMS.getSignerInfos();
            Collection<SignerInformation> c = signers.getSigners();
            if (c.size() != 1) {
                m_aLogger.severe("getFingerprint", "There is not exactly one signer!");
            } else {

                Iterator<SignerInformation> it = c.iterator();

                if (it.hasNext()) {
                    SignerInformation signer = it.next();
                    //grab date
                    AttributeTable att = signer.getSignedAttributes();
                    if (att.get(CMSAttributes.signingTime) == null) {
                        //no date
                        m_aLogger.info("getFingerprint()",
                                "A date is NOT present on CA root archive signature !");
                    } else {
                        Attribute atime = att.get(CMSAttributes.signingTime);
                        //date present
                        //@FIXME get date in a more clean way
                        String sdate = atime.getAttrValues().toString();
                        sDispDate = "20" + sdate.substring(1, 3) + "-" + sdate.substring(3, 5) + "-"
                                + sdate.substring(5, 7) + " " + sdate.substring(7, 9) + ":"
                                + sdate.substring(9, 11) + ":" + sdate.substring(11, 13) + " UTC";
                        m_aLogger.debug("getFingerprint()", "A date is present: " + sDispDate);
                    }

                    Collection<?> certCollection = null;
                    try {
                        certCollection = certs.getCertificates(signer.getSID());

                        if (certCollection.size() == 1) {
                            m_aRootSignatureCert = (X509Certificate) certCollection.toArray()[0];
                            fingerprint = getCertFingerprint(m_aRootSignatureCert);
                        } else {
                            //print an error?
                            m_aLogger.severe("getFingerprint",
                                    "There is not exactly one certificate for this signer!");
                        }
                    } catch (CertStoreException ex1) {
                        //print an error?
                        m_aLogger.severe("Errore nel CertStore", ex1);
                    }
                }
            }
        }

        //grab the localized text to display
        String _format = "id_root_verify_message";
        String _title = "id_root_verify_message_title";
        String _no_fp = "id_root_verify_message_ko";
        MessageConfigurationAccess m_aRegAcc = null;
        m_aRegAcc = new MessageConfigurationAccess(m_xCC, m_xMCF);

        try {
            _title = m_aRegAcc.getStringFromRegistry(_title);
            _format = m_aRegAcc.getStringFromRegistry(_format);
            _no_fp = m_aRegAcc.getStringFromRegistry(_no_fp);
        } catch (Exception e) {
            m_aLogger.severe(e);
        }
        m_aRegAcc.dispose();

        String theFingerprint = ((fingerprint == null) ? _no_fp : formatAsGUString(fingerprint));
        String _mex = String.format(_format, sDispDate, theFingerprint);

        DialogRootVerify aDialog1 = new DialogRootVerify(m_xFrame, m_xCC, m_xMCF, _mex);
        //      DialogRootVerify aDialog1 = new DialogRootVerify( null, m_xCC, m_xMCF,_mex );
        //PosX and PosY should be obtained from the parent window (in this case the frame)
        //the problem is that we get the pixel, but we need the logical pixel, so for now it doesn't work...
        int BiasX = ControlDims.RSC_SP_DLG_INNERBORDER_LEFT;
        int BiasY = ControlDims.RSC_SP_DLG_INNERBORDER_TOP;
        short ret;
        try {
            aDialog1.initialize(BiasX, BiasY);
            ret = aDialog1.executeDialog();
            // ret = 0: NO
            // ret = 1: Yes
            if (ret == 1) {
                return fingerprint;
            }
        } catch (BasicErrorException e) {
            m_aLogger.severe(e);
        } catch (Exception e) {
            m_aLogger.severe(e);
        }
    } catch (FileNotFoundException ex) {
        m_aLogger.severe("getFingerprint", "Errore nella lettura del file delle RootCA: ", ex);
    } catch (CMSException e) {
        m_aLogger.severe("getFingerprint", "Errore nel CMS delle RootCA: ", e);
    }
    return null;
}

From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java

License:Open Source License

/**
 * @param signerInformation//from w w  w . ja  v a 2s  .co  m
 * @return the existing signed attributes or an empty attributes hashtable
 */
public static AttributeTable getSignedAttributes(final SignerInformation signerInformation) {
    final AttributeTable signedAttributes = signerInformation.getSignedAttributes();
    if (signedAttributes == null) {
        return new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Attribute>());
    } else {
        return signedAttributes;
    }
}

From source file:id.govca.detachedsignature.CMSController.java

public boolean VerifyCMS(CMSSignedData signedData, String content_digest) throws IOException, CMSException,
        CertificateException, OperatorCreationException, UnmatchedSignatureException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        StringFormatException, ParseException, GeneralSecurityException {
    rootCertCandidate = null;//from  w  w  w  .ja v a 2  s. c  o  m

    Security.addProvider(new BouncyCastleProvider());

    byte[] dataku = (byte[]) signedData.getSignedContent().getContent();
    System.out.format("%-32s%s\n", "Base64 of Signed Content", Hex.toHexString(dataku));

    Store store = signedData.getCertificates();

    CertStore certsAndCRLs = new JcaCertStoreBuilder().setProvider("BC")
            .addCertificates(signedData.getCertificates()).build();

    // Verify signature
    SignerInformationStore signers = signedData.getSignerInfos();
    Collection c = signers.getSigners();
    System.out.format("%-32s%s\n", "Number of Signers", c.size());

    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        AttributeTable att = signer.getSignedAttributes();

        Attribute mdAtt = att.get(CMSAttributes.messageDigest);
        ASN1Primitive asp = mdAtt.getAttrValues().getObjectAt(0).toASN1Primitive();
        byte[] hasil = asp.getEncoded("DER");

        System.out.format("%-32s%s\n", "Digest of Signature", Hex.toHexString(hasil));

        Collection certCollection = store.getMatches(signer.getSID());
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC");

        ArrayList<X509CertificateHolder> listCertDatFirm = new ArrayList(store.getMatches(null));
        System.out.format("%-32s%d\n", "Number of cert Holders All", listCertDatFirm.size());

        try {
            verifyChain(listCertDatFirm);
        } catch (CertificateVerificationException ex) {
            System.out.println("CERTIFICATE CHAIN VERIFICATION FAILED");
            Logger.getLogger(CMSController.class.getName()).log(Level.SEVERE, null, ex);
            throw new UnmatchedSignatureException("Certificate Chain verification failed");
        }
        System.out.println("CERTIFICATE CHAIN VERIFIED");

        Collection<X509CertificateHolder> holders = store.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider()).getCertificate(certHolder);

        Principal princ = certFromSignedData.getIssuerDN();

        //Get Signer Name
        Principal p = certFromSignedData.getSubjectDN();
        System.out.format("%-32s%s\n", "Signer Distinguished Name", p.getName());

        this.setDN_fields(StringHelper.DNFieldsMapper(p.getName()));

        //Get Signing Time
        org.bouncycastle.asn1.cms.Attribute signingTime = att
                .get(new ASN1ObjectIdentifier("1.2.840.113549.1.9.5"));
        String asn1time = signingTime.getAttrValues().toString();
        System.out.format("%-32s%s\n", "Signing Time (RAW format)", asn1time);

        Date signtime = StringHelper.ASN1DateParser(asn1time);
        SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
        String formattedDate = formatter.format(signtime);
        System.out.format("%-32s%s\n", "Signing Time (Pretty format)", formattedDate);

        PublicKey pubkey = certFromSignedData.getPublicKey();

        if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider())
                .build(certFromSignedData))) {
            System.out.println("SIGNATURE VERIFIED <BY BOUNCY CASTLE STANDARD>");
        } else {
            System.out.println("SIGNATURE VERIFICATION <BY BOUNCY CASTLE STANDARD> FAILED");
            throw new UnmatchedSignatureException(
                    "Signature verification failed, probably the signature (CMS) has been altered!");
        }

        Cipher RSADecrypter;

        RSADecrypter = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

        //Initialize the Cipher using our the first key in the keystore  works fine for both
        RSADecrypter.init(Cipher.DECRYPT_MODE, pubkey);
        byte[] try_decrypt = RSADecrypter.doFinal(dataku);

        String decrypt_result = Hex.toHexString(try_decrypt);
        //Because there is magic number for hash algorithm at the beginning of the string,
        //we only need the last 64 characters from the decryption result
        String sanitized_decrypt_result = decrypt_result.substring(decrypt_result.length() - 64);

        System.out.format("%-32s%s\n", "Decryption Result", decrypt_result);
        System.out.format("%-32s%s\n", "Sanitized Decryption Result", sanitized_decrypt_result);

        if (!content_digest.equals(sanitized_decrypt_result)) {
            System.out.println("CONTENT DIGEST VERIFICATION FAILED");
            throw new UnmatchedSignatureException(
                    "Content digest verification failed, probably the content has been altered!");
        }
        System.out.println("CONTENT DIGEST VERIFIED");

        try {
            RootCertChecker rc = new RootCertChecker();

            rc.checkCertificate(rootCertCandidate, getRoot_cert_path());
        } catch (FileNotFoundException | InvalidKeyException | NoSuchAlgorithmException
                | NoSuchProviderException | SignatureException | CertificateException ex) {
            System.out.println("ROOT CERT VERIFICATION FAILED");
            throw new UnmatchedSignatureException("The System does not recognized this root Certificate");
        }
        System.out.println("ROOT CERTIFICATE VERIFIED");

    }

    return true;
}

From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java

License:Open Source License

private boolean isSameDigest(Collection<SignerInformation> sc1, Collection<SignerInformation> sc2) {

    boolean sameDigest = false;

    for (Iterator<SignerInformation> sc1i = sc1.iterator(); sc1i.hasNext();) {

        SignerInformation s1 = sc1i.next();

        AttributeTable s1Attrs = s1.getSignedAttributes();

        Attribute s1MdAttr = s1Attrs.get(CMSAttributes.messageDigest);

        byte[] s1Md = DEROctetString.getInstance(s1MdAttr.getAttrValues().getObjectAt(0)).getOctets();

        for (Iterator<SignerInformation> sc2i = sc2.iterator(); sc2i.hasNext();) {

            SignerInformation s2 = sc2i.next();

            AttributeTable s2Attrs = s2.getSignedAttributes();

            Attribute s2MdAttr = s2Attrs.get(CMSAttributes.messageDigest);
            byte[] s2Md = DEROctetString.getInstance(s2MdAttr.getAttrValues().getObjectAt(0)).getOctets();

            sameDigest = Arrays.equals(s1Md, s2Md);

            if (!sameDigest)
                return false;

        }/*from  w w  w.j av  a 2s  . co  m*/
    }

    return sameDigest;
}