List of usage examples for org.bouncycastle.cms SignerInformation verify
public boolean verify(SignerInformationVerifier verifier) throws CMSException
From source file:org.apache.kerby.pkix.SignedDataEngine.java
License:Apache License
/** * Validates a CMS SignedData using the public key corresponding to the private * key used to sign the structure./* w w w . ja v a 2 s. c o m*/ * * @param s * @return true if the signature is valid. * @throws Exception */ public static boolean validateSignedData(CMSSignedData s) throws Exception { Store certStore = s.getCertificates(); Store crlStore = s.getCRLs(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) { return false; } } Collection certColl = certStore.getMatches(null); Collection crlColl = crlStore.getMatches(null); if (certColl.size() != s.getCertificates().getMatches(null).size() || crlColl.size() != s.getCRLs().getMatches(null).size()) { return false; } return true; }
From source file:org.apache.pdfbox.examples.pdmodel.TestCreateSignature.java
License:Apache License
private void checkSignature(File file) throws IOException, CMSException, OperatorCreationException, GeneralSecurityException { PDDocument document = PDDocument.load(file); List<PDSignature> signatureDictionaries = document.getSignatureDictionaries(); if (signatureDictionaries.isEmpty()) { Assert.fail("no signature found"); }/*from w w w . ja va2 s . c o m*/ for (PDSignature sig : document.getSignatureDictionaries()) { COSString contents = (COSString) sig.getCOSObject().getDictionaryObject(COSName.CONTENTS); FileInputStream fis = new FileInputStream(file); byte[] buf = sig.getSignedContent(fis); fis.close(); // inspiration: // http://stackoverflow.com/a/26702631/535646 // http://stackoverflow.com/a/9261365/535646 CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(buf), contents.getBytes()); Store certificatesStore = signedData.getCertificates(); Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners(); SignerInformation signerInformation = signers.iterator().next(); Collection matches = certificatesStore.getMatches(signerInformation.getSID()); X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next(); X509Certificate certFromSignedData = new JcaX509CertificateConverter() .getCertificate(certificateHolder); Assert.assertEquals(certificate, certFromSignedData); // CMSVerifierCertificateNotValidException means that the keystore wasn't valid at signing time if (!signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) { Assert.fail("Signature verification failed"); } break; } document.close(); }
From source file:org.apache.pdfbox.examples.signature.ShowSignature.java
License:Apache License
/** * Verify a PKCS7 signature.//w w w . j a v a 2s . c o m * * @param byteArray the byte sequence that has been signed * @param contents the /Contents field as a COSString * @param sig the PDF signature (the /V dictionary) * @throws CertificateException * @throws CMSException * @throws StoreException * @throws OperatorCreationException */ private void verifyPKCS7(byte[] byteArray, COSString contents, PDSignature sig) throws CMSException, CertificateException, StoreException, OperatorCreationException { // inspiration: // http://stackoverflow.com/a/26702631/535646 // http://stackoverflow.com/a/9261365/535646 CMSProcessable signedContent = new CMSProcessableByteArray(byteArray); CMSSignedData signedData = new CMSSignedData(signedContent, contents.getBytes()); Store certificatesStore = signedData.getCertificates(); Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners(); SignerInformation signerInformation = signers.iterator().next(); Collection matches = certificatesStore.getMatches(signerInformation.getSID()); X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next(); X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder); System.out.println("certFromSignedData: " + certFromSignedData); certFromSignedData.checkValidity(sig.getSignDate().getTime()); if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) { System.out.println("Signature verified"); } else { System.out.println("Signature verification failed"); } }
From source file:org.bitrepository.protocol.security.BasicMessageAuthenticator.java
License:Open Source License
@Override public SignerId authenticateMessage(byte[] messageData, byte[] signatureData) throws MessageAuthenticationException { try {//from w ww . j a v a 2 s. c om CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(messageData), signatureData); SignerInformation signer = (SignerInformation) s.getSignerInfos().getSigners().iterator().next(); X509Certificate signingCert = permissionStore.getCertificate(signer.getSID()); SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder() .setProvider(SecurityModuleConstants.BC).build(signingCert); if (!signer.verify(verifier)) { throw new MessageAuthenticationException("Signature does not match the message. Indicated " + "certificate did not sign message. Certificate issuer: " + signingCert.getIssuerX500Principal().getName() + ", serial: " + signingCert.getSerialNumber()); } return signer.getSID(); } catch (PermissionStoreException e) { throw new MessageAuthenticationException(e.getMessage(), e); } catch (CMSException e) { throw new SecurityException(e.getMessage(), e); } catch (OperatorCreationException e) { throw new SecurityException(e.getMessage(), e); } }
From source file:org.cryptoworkshop.ximix.client.verify.SignedDataVerifier.java
License:Apache License
/** * Verify the passed in CMS signed data, return false on failure. * * @param cmsData a CMSSignedData object. * @return true if signature checks out, false if there is a problem with the signature or the path to its verifying certificate. *//*from w w w .j a va 2s . c o m*/ public boolean signatureVerified(CMSSignedData cmsData) { Store certs = cmsData.getCertificates(); SignerInformationStore signers = cmsData.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); SignerInformation signer = (SignerInformation) it.next(); try { PKIXCertPathBuilderResult result = checkCertPath(signer.getSID(), certs); X509Certificate cert = (X509Certificate) result.getCertPath().getCertificates().get(0); return signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)); } catch (Exception e) { return false; } }
From source file:org.cryptoworkshop.ximix.client.verify.SignedDataVerifier.java
License:Apache License
/** * Verify the passed in CMS signed data, return false on failure. * <p>//from w w w . ja v a 2 s . c om * Note: this method assumes the parser has been freshly created and its content not read or drained. * </p> * * @param cmsParser a CMSSignedData object. * @return true if signature checks out, false if there is a problem with the signature or the path to its verifying certificate. */ public boolean signatureVerified(CMSSignedDataParser cmsParser) throws IOException, CMSException { cmsParser.getSignedContent().drain(); Store certs = cmsParser.getCertificates(); SignerInformationStore signers = cmsParser.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); SignerInformation signer = (SignerInformation) it.next(); try { PKIXCertPathBuilderResult result = checkCertPath(signer.getSID(), certs); X509Certificate cert = (X509Certificate) result.getCertPath().getCertificates().get(0); return signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)); } catch (Exception e) { // TODO: logging? return false; } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESChecker.java
License:Open Source License
/** * Validation is done only on digital signatures with a single signer. Valid * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 = * OID Data 1.2.840.113549.1.7.1//ww w .j a v a 2s . c om * * @param content Is only necessary to inform if the PKCS7 package is NOT * ATTACHED type. If it is of type attached, this parameter will be * replaced by the contents of the PKCS7 package. * @param signedData Value in bytes of the PKCS7 package, such as the * contents of a ".p7s" file. It is not only signature as in the * case of PKCS1. */ // TODO: Implementar validao de co-assinaturas public boolean check(byte[] content, byte[] signedData) throws SignerException { Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = null; try { if (content == null) { if (this.checkHash) { cmsSignedData = new CMSSignedData(this.hashes, signedData); this.checkHash = false; } else { cmsSignedData = new CMSSignedData(signedData); } } else { if (this.getAttached(signedData, false) != null) { cmsSignedData = new CMSSignedData(signedData); } else { cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData); } } } catch (CMSException ex) { throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex); } // Quantidade inicial de assinaturas validadas int verified = 0; Store<?> certStore = cmsSignedData.getCertificates(); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); // Realizao da verificao bsica de todas as assinaturas while (it.hasNext()) { SignatureInformations signatureInfo = new SignatureInformations(); try { SignerInformation signerInfo = (SignerInformation) it.next(); SignerInformationStore signerInfoStore = signerInfo.getCounterSignatures(); logger.info("Foi(ram) encontrada(s) " + signerInfoStore.size() + " contra-assinatura(s)."); @SuppressWarnings("unchecked") Collection<?> certCollection = certStore.getMatches(signerInfo.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder); CRLValidator cV = new CRLValidator(); try { cV.validate(varCert); } catch (CertificateValidatorCRLException cvce) { signatureInfo.getValidatorErrors().add(cvce.getMessage()); logger.info(cvce.getMessage()); } catch (CertificateRevocationException cre) { signatureInfo.getValidatorErrors().add(cre.getMessage()); logger.info("certificado revogado"); } PeriodValidator pV = new PeriodValidator(); try { pV.validate(varCert); } catch (CertificateValidatorException cve) { signatureInfo.getValidatorErrors().add(cve.getMessage()); } if (signerInfo.verify( new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) { verified++; logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified)); } // recupera atributos assinados logger.info(cadesMessagesBundle.getString("info.signed.attribute")); String varOIDPolicy = PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId(); AttributeTable signedAttributes = signerInfo.getSignedAttributes(); if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); logger.info(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); //throw new SignerException(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); } else { //Validando atributos assinados de acordo com a politica Attribute idSigningPolicy = null; idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(varOIDPolicy)); if (idSigningPolicy == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", varOIDPolicy)); } else { for (Enumeration<?> p = idSigningPolicy.getAttrValues().getObjects(); p .hasMoreElements();) { String policyOnSignature = p.nextElement().toString(); for (PolicyFactory.Policies pv : PolicyFactory.Policies.values()) { if (policyOnSignature.contains(pv.getUrl())) { setSignaturePolicy(pv); break; } } } } } Date dataHora = null; if (signedAttributes != null) { // Valida o atributo ContentType Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType); if (attributeContentType == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); //throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); logger.info( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.content.not.data")); //throw new SignerException(cadesMessagesBundle.getString("error.content.not.data")); logger.info(cadesMessagesBundle.getString("error.content.not.data")); } // Validando o atributo MessageDigest Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest")); } // Mostra data e hora da assinatura, no carimbo de tempo Attribute timeAttribute = signedAttributes.get(CMSAttributes.signingTime); if (timeAttribute != null) { dataHora = (((ASN1UTCTime) timeAttribute.getAttrValues().getObjectAt(0)).getDate()); logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora)); } else { logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D")); } } if (signaturePolicy == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.policy.on.component.not.found", varOIDPolicy)); logger.info(cadesMessagesBundle.getString("error.policy.on.component.not.found")); } else { if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules() .getSignerRules().getMandatedSignedAttr().getObjectIdentifiers()) { String oi = objectIdentifier.getValue(); Attribute signedAtt = signedAttributes.get(new ASN1ObjectIdentifier(oi)); logger.info(oi); if (signedAtt == null) { signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString( "error.signed.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue())); } } } } // recupera os atributos NO assinados logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); AttributeTable unsignedAttributes = signerInfo.getUnsignedAttributes(); if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) { // Apenas info pois a RB no tem atributos no assinados logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found")); } if (signaturePolicy != null) { // Validando atributos NO assinados de acordo com a politica if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules() .getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers()) { String oi = objectIdentifier.getValue(); Attribute unSignedAtt = unsignedAttributes.get(new ASN1ObjectIdentifier(oi)); logger.info(oi); if (unSignedAtt == null) { signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString( "error.unsigned.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue())); } if (oi.equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) { //Verificando timeStamp try { byte[] varSignature = signerInfo.getSignature(); Timestamp varTimeStampSigner = validateTimestamp(unSignedAtt, varSignature); signatureInfo.setTimeStampSigner(varTimeStampSigner); } catch (Exception ex) { signatureInfo.getValidatorErrors().add(ex.getMessage()); // nas assinaturas feitas na applet o unsignedAttributes.get gera exceo. } } if (oi.equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) { logger.info("++++++++++ EscTimeStamp ++++++++++++"); } } } } LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance() .getCertificateChain(varCert); if (varChain.size() < 3) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN())); logger.info(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN())); } signatureInfo.setSignDate(dataHora); signatureInfo.setChain(varChain); signatureInfo.setSignaturePolicy(signaturePolicy); this.getSignaturesInfo().add(signatureInfo); } catch (OperatorCreationException | java.security.cert.CertificateException ex) { signatureInfo.getValidatorErrors().add(ex.getMessage()); logger.info(ex.getMessage()); } catch (CMSException ex) { // When file is mismatch with sign if (ex instanceof CMSSignerDigestMismatchException) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signature.mismatch")); logger.info(cadesMessagesBundle.getString("error.signature.mismatch")); throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex); } else { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signature.invalid")); logger.info(cadesMessagesBundle.getString("error.signature.invalid")); throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex); } } catch (ParseException e) { signatureInfo.getValidatorErrors().add(e.getMessage()); logger.info(e.getMessage()); } } logger.info(cadesMessagesBundle.getString("info.signature.verified", verified)); // TODO Efetuar o parsing da estrutura CMS return true; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
/** * Validation is done only on digital signatures with a single signer. Valid * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 = * OID Data 1.2.840.113549.1.7.1//from w w w . j a va2s.co m * * @param content Is only necessary to inform if the PKCS7 package is NOT * ATTACHED type. If it is of type attached, this parameter will be * replaced by the contents of the PKCS7 package. * @param signedData Value in bytes of the PKCS7 package, such as the * contents of a ".p7s" file. It is not only signature as in the * case of PKCS1. * @deprecated moved to CadESChecker */ @SuppressWarnings("unchecked") @Override public boolean check(byte[] content, byte[] signedData) throws SignerException { Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = null; try { if (content == null) { if (this.checkHash) { cmsSignedData = new CMSSignedData(this.hashes, signedData); this.checkHash = false; } else { cmsSignedData = new CMSSignedData(signedData); } } else { cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData); } } catch (CMSException ex) { throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex); } // Quantidade inicial de assinaturas validadas int verified = 0; Store<?> certStore = cmsSignedData.getCertificates(); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); // Realizao da verificao bsica de todas as assinaturas while (it.hasNext()) { try { SignerInformation signer = (SignerInformation) it.next(); SignerInformationStore s = signer.getCounterSignatures(); SignatureInformations si = new SignatureInformations(); logger.info("Foi(ram) encontrada(s) " + s.size() + " contra-assinatura(s)."); Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder); PeriodValidator pV = new PeriodValidator(); try { pV.validate(varCert); } catch (CertificateValidatorException cve) { si.getValidatorErrors().add(cve.getMessage()); } CRLValidator cV = new CRLValidator(); try { cV.validate(varCert); } catch (CertificateValidatorCRLException cvce) { si.getValidatorErrors().add(cvce.getMessage()); } if (signer.verify( new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) { verified++; logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified)); } // Realiza a verificao dos atributos assinados logger.info(cadesMessagesBundle.getString("info.signed.attribute")); AttributeTable signedAttributes = signer.getSignedAttributes(); if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) { throw new SignerException( cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); } // Realiza a verificao dos atributos no assinados logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); AttributeTable unsignedAttributes = signer.getUnsignedAttributes(); if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) { logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found")); } // Mostra data e hora da assinatura, no carimbo de tempo Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime); Date dataHora = null; if (signingTime != null) { dataHora = (((ASN1UTCTime) signingTime.getAttrValues().getObjectAt(0)).getDate()); logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora)); } else { logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D")); } logger.info(cadesMessagesBundle.getString("info.attribute.validation")); // Valida o atributo ContentType Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType); if (attributeContentType == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { throw new SignerException(cadesMessagesBundle.getString("error.content.not.data")); } // Validando o atributo MessageDigest Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest")); } // Validando o atributo MessageDigest Attribute idSigningPolicy = null; idSigningPolicy = signedAttributes .get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId())); if (idSigningPolicy == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy")); } //Verificando timeStamp try { Attribute attributeTimeStamp = null; attributeTimeStamp = unsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())); if (attributeTimeStamp != null) { byte[] varSignature = signer.getSignature(); Timestamp varTimeStampSigner = validateTimestamp(attributeTimeStamp, varSignature); si.setTimeStampSigner(varTimeStampSigner); } } catch (Exception ex) { // nas assinaturas feitas na applet o unsignedAttributes.get gera exceo. } LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance() .getCertificateChain(varCert); si.setSignDate(dataHora); si.setChain(varChain); si.setSignaturePolicy(signaturePolicy); this.getSignatureInfo().add(si); } catch (OperatorCreationException | java.security.cert.CertificateException ex) { throw new SignerException(ex); } catch (CMSException ex) { // When file is mismatch with sign if (ex instanceof CMSSignerDigestMismatchException) throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex); else throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex); } catch (ParseException e) { throw new SignerException(e); } } logger.info(cadesMessagesBundle.getString("info.signature.verified", verified)); // TODO Efetuar o parsing da estrutura CMS return true; }
From source file:org.demoiselle.signer.timestamp.connector.TimeStampOperator.java
License:Open Source License
/** * Validate a time stamp//from www . j a v a2s . c o m * * @param content if it is assigned, the parameter hash must to be null * @param timeStamp timestamp to be validated * @param hash if it is assigned, the parameter content must to be null * @throws CertificateCoreException validate exception */ @SuppressWarnings("unchecked") public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException { try { TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp)); CMSSignedData s = timeStampToken.toCMSSignedData(); int verified = 0; Store<?> certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); while (it.hasNext()) { SignerInformation signer = it.next(); Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC") .build(cert); if (signer.verify(siv)) { verified++; } cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue(); timeStampToken.validate(siv); } logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified)); //Valida o hash incluso no carimbo de tempo com hash do arquivo carimbado byte[] calculatedHash = null; if (content != null) { Digest digest = DigestFactory.getInstance().factoryDefault(); TimeStampTokenInfo info = timeStampToken.getTimeStampInfo(); ASN1ObjectIdentifier algOID = info.getMessageImprintAlgOID(); digest.setAlgorithm(algOID.toString()); calculatedHash = digest.digest(content); } else { calculatedHash = hash; } if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) { logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok")); } else { throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok")); } } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) { throw new CertificateCoreException(ex.getMessage()); } }
From source file:org.dihedron.crypto.operations.verify.pkcs7.PKCS7Verifier.java
License:Open Source License
@SuppressWarnings("unchecked") private boolean verify(CMSSignedData signed, byte[] data) throws CryptoException { try {/* ww w . ja v a2 s . c om*/ logger.debug("starting CMSSignedData verification ... "); SignerInformationStore signers = signed.getSignerInfos(); Store certificates = signed.getCertificates(); logger.debug("{} signers found", signers.getSigners().size()); // loop over signers and their respective certificates and check if // the signature is verified (no check is made on certificates); exit // as soon as a verification fails, otherwise return a sound "verified" for (SignerInformation signer : (Iterable<SignerInformation>) signers.getSigners()) { logger.debug("{} certificates found for signer '{}'", certificates.getMatches(signer.getSID()).size(), signer.getSID()); for (Object certificate : certificates.getMatches(signer.getSID())) { if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC") .build((X509CertificateHolder) certificate))) { logger.info("signature verified for signer '{}'", signer.getSID()); } else { logger.error("signature verification failed for signer '{}'", signer.getSID()); return false; } } } logger.info("all signatures successfully verified"); return true; } catch (OperatorCreationException e) { logger.error("error creating operator", e); throw new CryptoException("Error creating operator", e); } catch (CertificateException e) { logger.error("invalid certificate", e); throw new CryptoException("Invalid certificate", e); } catch (CMSException e) { logger.error("CMS error", e); throw new CryptoException("CMS error", e); } }