Example usage for org.bouncycastle.asn1.cms CMSAttributes contentType

List of usage examples for org.bouncycastle.asn1.cms CMSAttributes contentType

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms CMSAttributes contentType.

Prototype

ASN1ObjectIdentifier contentType

To view the source code for org.bouncycastle.asn1.cms CMSAttributes contentType.

Click Source Link

Document

PKCS#9: 1.2.840.113549.1.9.3

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 w  w  .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");
    }//from   w  w  w . ja va  2 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");
    }//  w  ww. 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);
    }

    // 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  . j a  va2 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");
    }//ww w  .j a  va2 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 (!(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:es.gob.afirma.applet.CMSInformation.java

License:Open Source License

/**
 * Obtiene los atributos obligatorios de una firma.
 *
 * @param attributes    Grupo de atributos opcionales
 * @param binarySignType   Identifica el tipo de firma binaria (CMS o CADES)
 * @return              lista de atributos concatenados.
 *//*ww  w.  j a v  a  2s.  c o  m*/
private static String getsignedAttributes(final ASN1Set attributes, final int binarySignType) {
    String attributos = ""; //$NON-NLS-1$

    final Enumeration<?> e = attributes.getObjects();

    while (e.hasMoreElements()) {
        final ASN1Sequence a = (ASN1Sequence) e.nextElement();
        final ASN1ObjectIdentifier derIden = (ASN1ObjectIdentifier) a.getObjectAt(0);
        // tipo de contenido de la firma.
        if (derIden.equals(CMSAttributes.contentType)) {
            attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.22") + SP //$NON-NLS-1$
                    + a.getObjectAt(1) + CR;
        }
        //Message digest de  la firma
        if (derIden.equals(CMSAttributes.messageDigest)) {
            attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.43") + CR; //$NON-NLS-1$
        }
        //la fecha de firma. obtenemos y casteamos a algo legible.
        if (derIden.equals(CMSAttributes.signingTime)) {
            final ASN1Set time = (ASN1Set) a.getObjectAt(1);
            final DERUTCTime d = (DERUTCTime) time.getObjectAt(0);
            Date date = null;
            try {
                date = d.getDate();
            } catch (final ParseException ex) {
                Logger.getLogger("es.gob.afirma").warning("No es posible convertir la fecha"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            final SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss"); //$NON-NLS-1$
            final String ds = formatter.format(date);

            attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.39") + SP + ds + CR; //$NON-NLS-1$
        }
        if (binarySignType == BINARY_SIGN_CADES) {
            //atributo signing certificate v2
            if (derIden.equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2)) {
                attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.40") + CR; //$NON-NLS-1$
            }
            //Politica de firma.
            if (derIden.equals(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId)) {
                attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.41") + CR; //$NON-NLS-1$
            }
        }
    }
    return attributos;
}

From source file:es.gob.afirma.applet.CMSInformation.java

License:Open Source License

/**
 * Obtiene los atributos opcionales de una firma cualquiera.
 * En caso de ser EncryptedData, usar el otro metodo, ya que por construccion
 * no es posible utilizar este.// w w w  .ja v  a 2 s.c  o  m
 *
 * @param attributes    Grupo de atributos opcionales
 * @return              lista de atributos concatenados.
 */
private static String getUnSignedAttributes(final Enumeration<?> e) {
    String attributos = ""; //$NON-NLS-1$

    while (e.hasMoreElements()) {
        final ASN1Sequence a = (ASN1Sequence) e.nextElement();
        final ASN1ObjectIdentifier derIden = (ASN1ObjectIdentifier) a.getObjectAt(0);
        // tipo de contenido de la firma.
        if (derIden.equals(CMSAttributes.contentType)) {
            attributos = attributos + TB + AppletMessages.getString("CMSInformation.22") + SP + a.getObjectAt(1) //$NON-NLS-1$
                    + CR;
        }
        //Message digest de  la firma
        if (derIden.equals(CMSAttributes.messageDigest)) {
            attributos = attributos + TB + AppletMessages.getString("CMSInformation.43") + CR; //$NON-NLS-1$
        }
        //la fecha de firma. obtenemos y casteamos a algo legible.
        if (derIden.equals(CMSAttributes.signingTime)) {
            final ASN1Set time = (ASN1Set) a.getObjectAt(1);
            final DERUTCTime d = (DERUTCTime) time.getObjectAt(0);
            Date date = null;
            try {
                date = d.getDate();
            } catch (final ParseException ex) {
                Logger.getLogger("es.gob.afirma").warning("No es posible convertir la fecha"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            final SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss"); //$NON-NLS-1$
            final String ds = formatter.format(date);

            attributos = attributos + TB + AppletMessages.getString("CMSInformation.39") + SP + ds + CR; //$NON-NLS-1$
        }
        //contrafirma de la firma.
        if (derIden.equals(CMSAttributes.counterSignature)) {
            attributos = attributos + TB + AppletMessages.getString("CMSInformation.45") + CR; //$NON-NLS-1$
        }

    }
    return attributos;
}

From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java

License:Open Source License

/** Inicializa el contexto. */
static ASN1EncodableVector initContexExpecific(final String digestAlgorithm, final byte[] datos,
        final String dataType, final byte[] messageDigest) throws NoSuchAlgorithmException {
    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // tipo de contenido
    if (dataType != null) {
        contexExpecific//from ww w. j a va  2  s. c o m
                .add(new Attribute(CMSAttributes.contentType, new DERSet(new DERObjectIdentifier(dataType))));
    }

    // fecha de firma
    contexExpecific.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));

    // MessageDigest
    contexExpecific.add(new Attribute(CMSAttributes.messageDigest,
            new DERSet(new DEROctetString(messageDigest != null ? messageDigest
                    : MessageDigest.getInstance(digestAlgorithm).digest(datos)))));

    return contexExpecific;
}

From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedData.java

License:Open Source License

/** M&eacute;todo que genera la parte que contiene la informaci&oacute;n del
 * Usuario. Se generan los atributos que se necesitan para generar la firma.
 * @param cert// w  w w.  j  a  v a2  s  . c  o  m
 *        Certificado necesario para la firma.
 * @param digestAlgorithm
 *        Algoritmo Firmado.
 * @param datos
 *        Datos firmados.
 * @param datatype
 *        Identifica el tipo del contenido a firmar.
 * @param timestamp
 *        Introducir TimeStaming
 * @param atrib
 *        Lista de atributos firmados que se insertar&aacute;n dentro
 *        del archivo de firma.
 * @return Los atributos firmados de la firma.
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se encuentra un algoritmo v&aacute;lido. */
private static ASN1Set generateSignedAtt(final X509Certificate cert, final String digestAlgorithm,
        final byte[] datos, final String datatype, final boolean timestamp, final Map<String, byte[]> atrib)
        throws NoSuchAlgorithmException {

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // tipo de contenido
    contexExpecific
            .add(new Attribute(CMSAttributes.contentType, new DERSet(new ASN1ObjectIdentifier(datatype))));

    // fecha de firma
    if (timestamp) {
        contexExpecific.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));
    }

    // Si nos viene el hash de fuera no lo calculamos
    final byte[] md = MessageDigest.getInstance(AOSignConstants.getDigestAlgorithmName(digestAlgorithm))
            .digest(datos);

    // MessageDigest
    contexExpecific.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(md.clone()))));

    // Serial Number
    // comentar lo de abajo para version del rfc 3852
    contexExpecific.add(new Attribute(RFC4519Style.serialNumber,
            new DERSet(new DERPrintableString(cert.getSerialNumber().toString()))));

    // agregamos la lista de atributos a mayores.
    if (atrib.size() != 0) {

        final Iterator<Map.Entry<String, byte[]>> it = atrib.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, byte[]> e = it.next();
            contexExpecific.add(new Attribute(
                    // el oid
                    new ASN1ObjectIdentifier(e.getKey().toString()),
                    // el array de bytes en formato string
                    new DERSet(new DERPrintableString(new String(e.getValue())))));
        }

    }

    return SigUtils.getAttributeSet(new AttributeTable(contexExpecific));
}

From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedEnvelopedData.java

License:Open Source License

/** M&eacute;todo que genera la parte que contiene la informaci&oacute;n del
 * Usuario. Se generan los atributos que se necesitan para generar la firma.
 * @param datatype/* w ww  .  j ava  2 s  . com*/
 *        Identifica el tipo del contenido a firmar.
 * @param signingTime
 *        Introducir la hora de firma (tomada del sistema)
 * @param atrib
 *        Lista de atributos firmados que se insertar&aacute;n dentro
 *        del archivo de firma.
 * @return Los atributos firmados de la firma. */
private static ASN1Set generateSignedAtt(final String datatype, final boolean signingTime,
        final Map<String, byte[]> atrib) {

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // tipo de contenido
    contexExpecific
            .add(new Attribute(CMSAttributes.contentType, new DERSet(new ASN1ObjectIdentifier(datatype))));

    // fecha de firma
    if (signingTime) {
        contexExpecific.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));
    }

    // agregamos la lista de atributos a mayores.
    if (atrib.size() != 0) {

        final Iterator<Map.Entry<String, byte[]>> it = atrib.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, byte[]> e = it.next();
            contexExpecific.add(new Attribute(
                    // el oid
                    new ASN1ObjectIdentifier(e.getKey().toString()),
                    // el array de bytes en formato string
                    new DERSet(new DERPrintableString(new String(e.getValue())))));
        }

    }

    return SigUtils.getAttributeSet(new AttributeTable(contexExpecific));
}