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

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

Introduction

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

Prototype

ASN1ObjectIdentifier signingTime

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

Click Source Link

Document

PKCS#9: 1.2.840.113549.1.9.5

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  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())) {
        throw new SignerException("Algoritmo de resumo invlido para esta poltica");
    }

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

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

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

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

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

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

License:Open Source License

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

    if (contentSigned == null || contentSigned.length == 0) {
        throw new SignaturePolicyException("Content signed is null");
    }/*w  w  w  .  j av 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_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  w w  w .ja v a2 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);
    }

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

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

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

    }

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

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

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

}

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

License:Open Source License

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

    X509Certificate certificate = null;
    PublicKey publicKey = null;

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

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

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

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

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

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

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

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

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

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

    // 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 ww w.  j  a  va2  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 (!(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  2  s  . 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:de.brendamour.jpasskit.signing.PKAbstractSIgningUtil.java

License:Apache License

protected byte[] signManifestUsingContent(PKSigningInformation signingInformation, CMSTypedData content)
        throws PKSigningException {
    if (signingInformation == null || !signingInformation.isValid()) {
        throw new IllegalArgumentException("Signing information not valid");
    }//w w w  .ja  v a  2s.c o  m

    try {
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .build(signingInformation.getSigningPrivateKey());

        final ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
        final Attribute signingAttribute = new Attribute(CMSAttributes.signingTime,
                new DERSet(new DERUTCTime(new Date())));
        signedAttributes.add(signingAttribute);

        // Create the signing table
        final AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
        // Create the table table generator that will added to the Signer builder
        final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributesTable);

        generator.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                                .setSignedAttributeGenerator(signedAttributeGenerator)
                                .build(sha1Signer, signingInformation.getSigningCert()));

        List<X509Certificate> certList = new ArrayList<X509Certificate>();
        certList.add(signingInformation.getAppleWWDRCACert());
        certList.add(signingInformation.getSigningCert());

        JcaCertStore certs = new JcaCertStore(certList);

        generator.addCertificates(certs);

        CMSSignedData sigData = generator.generate(content, false);
        return sigData.getEncoded();
    } catch (Exception e) {
        throw new PKSigningException("Error when signing manifest", e);
    }
}

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.
 *//*from   w ww .j a v a 2  s .  com*/
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.//from  www .j  ava2s  . co 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  w  w  w . j  ava2  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;
}