Example usage for org.bouncycastle.asn1 DERSet getObjectAt

List of usage examples for org.bouncycastle.asn1 DERSet getObjectAt

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DERSet getObjectAt.

Prototype

public ASN1Encodable getObjectAt(int index) 

Source Link

Document

return the object at the set position indicated by index.

Usage

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public static String extractHashId(byte[] sign) throws Exception {
    String ret = null;/*from   w w  w . j a  v a 2 s .c o m*/
    ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
    ASN1Primitive topLevel = is.readObject();
    LOG.debug("top level:" + topLevel.getClass().getName());

    if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
        DLSequence topLevelDLS = (DLSequence) topLevel;
        if (topLevelDLS.size() == 2) {
            ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
            LOG.debug("level1:" + level1.getClass().getName());
            if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
                DERTaggedObject level1TO = (DERTaggedObject) level1;
                ASN1Primitive level2 = level1TO.getObject();
                LOG.debug("level2:" + level2.getClass().getName());
                if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
                    DERSequence level2DS = (DERSequence) level2;
                    LOG.debug("level2 len:" + level2DS.size());

                    ASN1Encodable level3_1 = level2DS.getObjectAt(1);
                    LOG.debug("level3_1:" + level3_1.getClass().getName());

                    if (level3_1 instanceof org.bouncycastle.asn1.DERSet) {
                        DERSet level3_1Set = (DERSet) level3_1;
                        ASN1Encodable level4_1 = level3_1Set.getObjectAt(0);
                        LOG.debug("level4_1:" + level4_1.getClass().getName());

                        if (level4_1 instanceof org.bouncycastle.asn1.DERSequence) {
                            DERSequence level4_1Seq = (DERSequence) level4_1;
                            ASN1Encodable level5_0 = level4_1Seq.getObjectAt(0);

                            LOG.debug("level5_0:" + level5_0.getClass().getName());

                            if (level5_0 instanceof org.bouncycastle.asn1.ASN1ObjectIdentifier) {
                                ASN1ObjectIdentifier level5_0Seq = (ASN1ObjectIdentifier) level5_0;
                                LOG.debug(level5_0Seq.toString());
                                ret = level5_0Seq.toString();

                            } else {
                                throw new Exception("DER enconding error");
                            }

                        } else {
                            throw new Exception("DER enconding error");
                        }

                    } else {
                        throw new Exception("DER enconding error");
                    }
                } else {
                    throw new Exception("DER enconding error");
                }

            } else {
                throw new Exception("DER enconding error");
            }
        } else {
            throw new Exception("DER enconding error");
        }

    } else {
        throw new Exception("DER enconding error");
    }

    return ret;
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public static byte[] extractSignature(byte[] sign) throws Exception {
    byte[] ret = null;
    ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
    ASN1Primitive topLevel = is.readObject();
    LOG.debug("top level:" + topLevel.getClass().getName());

    if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
        DLSequence topLevelDLS = (DLSequence) topLevel;
        if (topLevelDLS.size() == 2) {
            ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
            LOG.debug("level1:" + level1.getClass().getName());
            if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
                DERTaggedObject level1TO = (DERTaggedObject) level1;
                ASN1Primitive level2 = level1TO.getObject();
                LOG.debug("level2:" + level2.getClass().getName());
                if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
                    DERSequence level2DS = (DERSequence) level2;
                    LOG.debug("level2 len:" + level2DS.size());
                    ASN1Encodable level3_4 = level2DS.getObjectAt(level2DS.size() - 1);
                    LOG.debug("level3_4:" + level3_4.getClass().getName());
                    if (level3_4 instanceof org.bouncycastle.asn1.DERSet) {
                        DERSet level3_4DS = (DERSet) level3_4;
                        ASN1Encodable level3_4_0 = level3_4DS.getObjectAt(0);
                        LOG.debug("level3_4_0:" + level3_4_0.getClass().getName());
                        if (level3_4_0 instanceof org.bouncycastle.asn1.DERSequence) {
                            DERSequence level3_4_0DS = (DERSequence) level3_4_0;
                            LOG.debug("level3_4_0DS len:" + level3_4_0DS.size());
                            ASN1Encodable signature = level3_4_0DS.getObjectAt(level3_4_0DS.size() - 1);
                            LOG.debug("signature:" + signature.getClass().getName());
                            if (signature instanceof org.bouncycastle.asn1.DEROctetString) {
                                DEROctetString signDOS = (DEROctetString) signature;
                                ret = signDOS.getOctets();
                            }//from   w  w w .  j  av a  2  s .co m
                        } else {
                            throw new Exception("DER enconding error");
                        }

                    } else {
                        throw new Exception("DER enconding error");
                    }
                } else {
                    throw new Exception("DER enconding error");
                }

            } else {
                throw new Exception("DER enconding error");
            }
        } else {
            throw new Exception("DER enconding error");
        }

    } else {
        throw new Exception("DER enconding error");
    }

    return ret;
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public static DERTaggedObject extractSignedAttributes(DERSequence level2DS) throws Exception {
    DERTaggedObject ret = null;//from   w w  w  . j  av  a 2s  . c o m

    ASN1Encodable level3_4 = level2DS.getObjectAt(level2DS.size() - 1);
    LOG.debug("level3_4:" + level3_4.getClass().getName());
    if (level3_4 instanceof org.bouncycastle.asn1.DERSet) {
        DERSet level3_4DS = (DERSet) level3_4;
        ASN1Encodable level3_4_0 = level3_4DS.getObjectAt(0);
        LOG.debug("level3_4_0:" + level3_4_0.getClass().getName());
        if (level3_4_0 instanceof org.bouncycastle.asn1.DERSequence) {
            DERSequence level3_4_0DS = (DERSequence) level3_4_0;
            LOG.debug("level3_4_0DS len:" + level3_4_0DS.size());
            ASN1Encodable signedAttribs = level3_4_0DS.getObjectAt(3);
            LOG.debug("signature:" + signedAttribs.getClass().getName());
            if (signedAttribs instanceof org.bouncycastle.asn1.DERTaggedObject) {
                DERTaggedObject signedAttribsDTO = (DERTaggedObject) signedAttribs;
                ret = signedAttribsDTO;

                // trata busca da Policy OID
            } else if (signedAttribs instanceof org.bouncycastle.asn1.DERSequence) {
                ret = null;
            } else {
                throw new Exception("DER enconding error");
            }
        } else {
            throw new Exception("DER enconding error");
        }

    } else {
        throw new Exception("DER enconding error");
    }
    return ret;
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public static void extractSignPolicyRefFromSignedAttrib(DERTaggedObject signedAttribsDTO,
        SignCompare signCompare) throws Exception {
    //      String SignCompare = null;
    ASN1Primitive dtoObj = signedAttribsDTO.getObject();
    if (dtoObj instanceof DLSequence) {
        DLSequence topSeq = (DLSequence) dtoObj;
        List<String> signedAttribOid = new ArrayList<String>();
        signCompare.setSignedAttribs(signedAttribOid);
        for (int i = 0; i < topSeq.size(); i++) {
            // treat each SIGNED ATTRIBUTE
            ASN1Encodable objL1 = topSeq.getObjectAt(i);
            if (objL1 instanceof DERSequence) {
                DERSequence seqL1 = (DERSequence) objL1;
                ASN1Encodable objL2 = seqL1.getObjectAt(0);
                if (objL2 instanceof ASN1ObjectIdentifier) {
                    ASN1ObjectIdentifier saOid = (ASN1ObjectIdentifier) objL2;
                    String saOIdStr = saOid.toString();
                    // System.out.println(saOIdStr);
                    signedAttribOid.add(saOIdStr);

                    if (saOIdStr.compareTo(DerEncoder.ID_SIG_POLICY) == 0) {
                        ASN1Encodable objL21 = seqL1.getObjectAt(1);
                        if (objL21 instanceof DERSet) {
                            DERSet objL21Set = (DERSet) objL21;
                            ASN1Encodable objL3 = objL21Set.getObjectAt(0);
                            if (objL3 instanceof DERSequence) {
                                DERSequence objL3Seq = (DERSequence) objL3;
                                ASN1Encodable objL4 = objL3Seq.getObjectAt(0);
                                if (objL4 instanceof ASN1ObjectIdentifier) {
                                    ASN1ObjectIdentifier objL4Oid = (ASN1ObjectIdentifier) objL4;
                                    signCompare.setPsOid(objL4Oid.toString());
                                }//from   w  ww.ja va2s  .  c  o m
                                ASN1Encodable objL42 = getAt(objL3Seq, 2);
                                if (objL42 instanceof DERSequence) {
                                    DERSequence objL42DerSeq = (DERSequence) objL42;
                                    ASN1Encodable objL420 = getAt(objL42DerSeq, 0);
                                    if (objL420 instanceof DERSequence) {
                                        DERSequence objL420DerSeq = (DERSequence) objL420;
                                        ASN1Encodable psUrl = getAt(objL420DerSeq, 1);
                                        if (psUrl instanceof DERIA5String) {
                                            DERIA5String psUrlIA5 = (DERIA5String) psUrl;
                                            signCompare.setPsUrl(psUrlIA5.getString());
                                        }
                                    }
                                }

                            }
                        }
                    } else if (saOIdStr.compareTo(DerEncoder.ID_SIGNING_TIME) == 0) {
                        ASN1Encodable objL2SetTime = seqL1.getObjectAt(1);
                        if (objL2SetTime instanceof DERSet) {
                            DERSet objL2SetTimeDer = (DERSet) objL2SetTime;
                            ASN1Encodable objL2SignTime = objL2SetTimeDer.getObjectAt(0);
                            if (objL2SignTime instanceof ASN1UTCTime) {
                                ASN1UTCTime objL2SignTimeUTC = (ASN1UTCTime) objL2SignTime;
                                signCompare.setSigningTime(objL2SignTimeUTC.getDate());
                            }

                        }

                    }
                }
            }
        }
    }

}

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");
    }//  w ww  . j a  v a 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 a  va  2s  .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  ww  .j a  v  a2 s. com*/

    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   www .  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");
    }//from w  w w .j a v  a 2s  .  co m

    X509Certificate certificate = null;
    PublicKey publicKey = null;

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

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

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

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

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

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

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

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

    String algorithm = SignerAlgorithmEnum
            .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString())
            .getAlgorithmHash();
    if (!(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:crossbear.CVRProcessor.java

License:Open Source License

/**
 * Search a DERSet for Common Names (identified by OID 2.5.4.3) and add all of them as byte[] to a Vector of byte[]s
 * /*  w  w w  .  j ava 2 s.  c  o m*/
 * @param set The DERSet to search
 * @param cnBytes The Vector to add all found CNs to
 * @throws IOException
 */
private static void searchSetForCN(DERSet set, Vector<byte[]> cnBytes) throws IOException {

    // The DERSet we are looking for contains exactly one element: a DERSequence
    if (set.size() != 1 || !(set.getObjectAt(0) instanceof DERSequence))
        return;

    // Extract the DERSequence
    DERSequence subseq = (DERSequence) set.getObjectAt(0);

    // The DERSequence we are looking for consists of two elements: an OID and the CN
    // First: Assert type of OID
    if (!(subseq.getObjectAt(0) instanceof ASN1ObjectIdentifier))
        return;

    // Second: Check value of OID to be id-at-commonName
    ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) subseq.getObjectAt(0);
    if (!id.getId().equals("2.5.4.3"))
        return;

    // Third extract the commonName
    cnBytes.add(subseq.getObjectAt(1).getDERObject().getEncoded());
}