List of usage examples for org.bouncycastle.cms CMSSignedData CMSSignedData
public CMSSignedData(ContentInfo sigData) throws CMSException
From source file:be.e_contract.mycarenet.certra.CertRAClient.java
License:Open Source License
private byte[] getCmsData(byte[] cms) throws Exception { CMSSignedData cmsSignedData = new CMSSignedData(cms); SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); Store certificateStore = cmsSignedData.getCertificates(); Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId); X509CertificateHolder certificateHolder = certificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded())); // we trust SSL here, no need for explicit verification of CMS signing // certificate LOG.debug("CMS signing certificate subject: " + certificate.getSubjectX500Principal()); SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(certificate);/*from w w w . ja v a 2 s . c o m*/ boolean signatureResult = signer.verify(signerInformationVerifier); if (false == signatureResult) { throw new SecurityException("woops"); } CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] responseData = (byte[]) signedContent.getContent(); return responseData; }
From source file:be.e_contract.mycarenet.etee.EncryptionToken.java
License:Open Source License
private X509Certificate parseEncryptionCertificate(byte[] encodedEncryptionToken) throws CMSException, CertificateException, IOException, OperatorCreationException { CMSSignedData cmsSignedData = new CMSSignedData(encodedEncryptionToken); // get signer identifier SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); // get signer certificate Store certificateStore = cmsSignedData.getCertificates(); LOG.debug("certificate store type: " + certificateStore.getClass().getName()); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> signingCertificateCollection = certificateStore.getMatches(signerId); X509CertificateHolder signingCertificateHolder = signingCertificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate signingCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(signingCertificateHolder.getEncoded())); LOG.debug("signing certificate: " + signingCertificate.getSubjectX500Principal()); // verify CMS signature SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(signingCertificate);/* ww w . j a v a 2s . co m*/ boolean signatureResult = signer.verify(signerInformationVerifier); if (false == signatureResult) { throw new SecurityException("ETK signature invalid"); } // get encryption certificate CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] data = (byte[]) signedContent.getContent(); X509Certificate encryptionCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(data)); LOG.debug("all available certificates:"); logCertificates(certificateStore, null); // get authentication certificate CustomSelector authenticationSelector = new CustomSelector(); authenticationSelector.setSubject(encryptionCertificate.getIssuerX500Principal()); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> authenticationCertificates = certificateStore .getMatches(authenticationSelector); if (authenticationCertificates.size() != 1) { LOG.debug("no authentication certificate match"); } X509CertificateHolder authenticationCertificateHolder = authenticationCertificates.iterator().next(); this.authenticationCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(authenticationCertificateHolder.getEncoded())); verifyProxyCertificate(encryptionCertificate, this.authenticationCertificate); return encryptionCertificate; }
From source file:be.e_contract.mycarenet.etee.Unsealer.java
License:Open Source License
private byte[] getVerifiedContent(byte[] cmsData) throws CertificateException, CMSException, IOException, OperatorCreationException { CMSSignedData cmsSignedData = new CMSSignedData(cmsData); SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); Store certificateStore = cmsSignedData.getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId); if (null == this.senderCertificate) { if (certificateCollection.isEmpty()) { throw new SecurityException("no sender certificate present"); }/* www . jav a 2s .co m*/ X509CertificateHolder certificateHolder = certificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded())); this.senderCertificate = certificate; LOG.debug("signer certificate subject: " + certificate.getSubjectX500Principal()); } /* * By reusing the sender certificate we have the guarantee that the * outer signature and inner signature share the same origin. */ SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(this.senderCertificate); boolean signatureResult = signer.verify(signerInformationVerifier); if (false == signatureResult) { throw new SecurityException("woops"); } CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] data = (byte[]) signedContent.getContent(); return data; }
From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java
License:Open Source License
/** * Gives back all time-stamp tokens embedded within the given XAdES * time-stamp container./*from w w w . j ava2s. c o m*/ * * @param xadesTimeStamp * @return * @throws XAdESValidationException */ public static List<TimeStampToken> getTimeStampTokens(XAdESTimeStampType xadesTimeStamp) throws XAdESValidationException { try { List<TimeStampToken> timeStampTokens = new LinkedList<TimeStampToken>(); for (Object timeStampTokenObject : xadesTimeStamp.getEncapsulatedTimeStampOrXMLTimeStamp()) { if (timeStampTokenObject instanceof EncapsulatedPKIDataType) { EncapsulatedPKIDataType encapsulatedTimeStampToken = (EncapsulatedPKIDataType) timeStampTokenObject; byte[] encodedTimestampToken = encapsulatedTimeStampToken.getValue(); timeStampTokens.add(new TimeStampToken(new CMSSignedData(encodedTimestampToken))); } else { throw new XAdESValidationException( "Timestamp token of type: " + timeStampTokenObject.getClass() + " not supported."); } } return timeStampTokens; } catch (Exception e) { throw new XAdESValidationException(e); } }
From source file:be.fedict.trust.service.bean.TrustServiceBean.java
License:Open Source License
@TransactionAttribute(TransactionAttributeType.REQUIRED) @SNMP(oid = SnmpConstants.VALIDATE_TSA)/*w w w . j a v a2 s.co m*/ public ValidationResult validateTimestamp(String trustDomainName, byte[] encodedTimestampToken, boolean returnRevocationData) throws TSPException, IOException, CMSException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, TrustDomainNotFoundException { LOG.debug("validate timestamp token"); /* * Parse embedded certificate chain */ List<X509Certificate> certificateChain = new LinkedList<X509Certificate>(); TimeStampToken timestampToken = new TimeStampToken(new CMSSignedData(encodedTimestampToken)); CertStore certStore = timestampToken.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> certificates = certStore.getCertificates(null); for (Certificate certificate : certificates) { certificateChain.add((X509Certificate) certificate); } if (TrustValidator.isSelfSigned(certificateChain.get(0))) { Collections.reverse(certificateChain); } /* * Validate */ TrustLinkerResult lastResult = null; RevocationData lastRevocationData = null; for (TrustDomainEntity trustDomain : getTrustDomains(trustDomainName)) { TrustValidator trustValidator = getTrustValidator(trustDomain, returnRevocationData); try { trustValidator.isTrusted(certificateChain); } catch (CertPathValidatorException ignored) { } if (trustValidator.getResult().isValid()) { LOG.debug("valid for trust domain: " + trustDomain.getName()); harvest(trustDomain, certificateChain); return new ValidationResult(trustValidator.getResult(), trustValidator.getRevocationData()); } lastResult = trustValidator.getResult(); lastRevocationData = trustValidator.getRevocationData(); } return new ValidationResult(lastResult, lastRevocationData); }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java
License:Open Source License
/** * A validao se basea apenas em assinaturas com um assinante apenas. * Valida apenas com o contedo do tipo DATA: OID ContentType * 1.2.840.113549.1.9.3 = OID Data 1.2.840.113549.1.7.1 * * @param content//from w ww . j a va 2 s. c om * @param signed * @return * @params content Necessrio informar apenas se o pacote PKCS7 NO for do * tipo ATTACHED. Caso seja do tipo attached, este parmetro ser * substituido pelo contedo do pacote PKCS7. * @params signed Valor em bytes do pacote PKCS7, como por exemplo o * contedo de um arquivo ".p7s". No a assinatura pura como no caso do * PKCS1. TODO: Implementar validao de co-assinaturas */ @Override public boolean check(byte[] content, byte[] signed) { CMSSignedData signedData = null; PublicKey publicKey = null; try { if (content == null) { signedData = new CMSSignedData(signed); } else { signedData = new CMSSignedData(new CMSProcessableByteArray(content), signed); } } catch (CMSException exception) { throw new SignerException("Invalid bytes for a PKCS7 package", exception); } SignerInformationStore signerInformationStore = signedData.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); /* * Retirando o Certificado Digital e a chave Pblica da assinatura */ try { CertStore certs; try { Security.addProvider(new BouncyCastleProvider()); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> collCertificados = certs .getCertificates(signerInformation.getSID()); if (!collCertificados.isEmpty()) { certificate = (X509Certificate) collCertificados.iterator().next(); publicKey = certificate.getPublicKey(); } } catch (NoSuchAlgorithmException exception) { throw new SignerException(exception); } catch (NoSuchProviderException exception) { throw new SignerException(exception); } catch (CMSException exception) { throw new SignerException(exception); } catch (CertStoreException exception) { throw new SignerException(exception); } } catch (SignerException ex) { throw new SignerException( "Error on get information about certificates and public keys from a package PKCS7", ex); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } AttributeTable signedAttributes = signerInformation.getSignedAttributes(); if (signedAttributes == null) { throw new SignerException("Package PKCS7 without signed attributes"); } // Validar a poltica org.bouncycastle.asn1.cms.Attribute signaturePolicyIdentifierAttribute = signedAttributes .get(new DERObjectIdentifier((new SignaturePolicyIdentifier()).getOID())); if (signaturePolicyIdentifierAttribute != null) { ASN1Set valueAttribute = signaturePolicyIdentifierAttribute.getAttrValues(); for (Enumeration<DERSequence> iterator = valueAttribute.getObjects(); iterator.hasMoreElements();) { DERSequence sequence = iterator.nextElement(); DERObjectIdentifier policyIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0); String policyOID = policyIdentifier.getId(); SignaturePolicy policy = SignaturePolicyFactory.getInstance().factory(policyOID); if (policy != null) { policy.validate(content, signed); } else { LOGGER.log(Level.WARNING, "N\u00e3o existe validador para a pol\u00edtica {0}", policyOID); } } } else { throw new SignerException("ICP-Brasil invalid format. There is not policy signature."); } return true; }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java
License:Open Source License
@Override public byte[] getAttached(byte[] signed, boolean validate) { byte[] result = null; if (validate) { this.check(null, signed); }// w w w . j a va2 s .c o m CMSSignedData signedData = null; try { signedData = new CMSSignedData(signed); } catch (CMSException exception) { throw new SignerException("Invalid bytes for a package PKCS7", exception); } try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { result = (byte[]) contentProcessable.getContent(); } } catch (Exception exception) { throw new SignerException("Error on get content from PKCS7", exception); } return result; }
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"); }/* www . ja 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"); }//from w w w . j a v a2s. 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_1.getAlgorithm()) && !algorithm.equals(DigestAlgorithmEnum.SHA_256.getAlgorithm())) { throw new SignerException("Algoritmo de resumo invlido para esta poltica"); } Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(algorithm); byte[] hashContent = digest.digest(content); if (!MessageDigest.isEqual(hashContentSigned, hashContent)) { throw new SignerException("Hash not equal"); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } // O atributo signingCertificate deve conter referncia apenas ao // certificado do signatrio. org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.12")); if (signedSigningCertificate != null) { // Uso futuro, para processamento dos valores ASN1Set set = signedSigningCertificate.getAttrValues(); } else { throw new SignerException("O Atributo signingCertificate no pode ser nulo."); } // Valida a cadeia de certificao de um arquivo assinado //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_1_1, CertPathEncoding.PKCS7); Date dataSigner = null; try { org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable .get(CMSAttributes.signingTime); ASN1Set valorDateSigner = attributeSigningTime.getAttrValues(); DERSet derSet = (DERSet) valorDateSigner.getDERObject(); DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0); dataSigner = time.getAdjustedDate(); } catch (Throwable error) { throw new SignerException("SigningTime error", error); } //Para a verso 1.1, o perodo para assinatura desta PA de 26/12/2011 a 29/02/2012. // Calendar calendar = GregorianCalendar.getInstance(); // calendar.set(2011, Calendar.DECEMBER, 26, 0, 0, 0); // Date firstDate = calendar.getTime(); // // calendar.set(2012, Calendar.FEBRUARY, 29, 23, 59, 59); // Date lastDate = calendar.getTime(); // // if (dataSigner != null) { // if (dataSigner.before(firstDate)) { // throw new SignerException("Invalid signing time. Not valid before 12/26/2011"); // } // if (dataSigner.after(lastDate)) { // throw new SignerException("Invalid signing time. Not valid after 02/29/2012"); // } // } else { // throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null"); // } }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_2_0.java
License:Open Source License
@Override public void validate(byte[] content, byte[] contentSigned) { if (contentSigned == null || contentSigned.length == 0) { throw new SignaturePolicyException("Content signed is null"); }/*w w w . jav a2s . 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"); } }