List of usage examples for org.bouncycastle.cms SignerInformation verify
public boolean verify(SignerInformationVerifier verifier) throws CMSException
From source file:it.trento.comune.j4sign.cms.utils.CMSVerifier.java
License:Open Source License
public void basicVerify() { addBCProvider();/*from w w w . j a va 2s . c o m*/ SimpleDateFormat df = new SimpleDateFormat("dd MMMMM yyyy HH:mm:ss z"); try { Store certs = this.cmsSignedData.getCertificates(); // Recupero i firmatari. SignerInformationStore signerStore = this.cmsSignedData.getSignerInfos(); Collection<SignerInformation> c = signerStore.getSigners(); if (debug) System.out.println(c.size() + " firmatari diversi trovati"); Iterator<SignerInformation> it = c.iterator(); // ciclo tra tutti i firmatari int i = 0; X509Certificate cert = null; while (it.hasNext()) { SignerInformation signer = it.next(); Collection<?> certCollection = null; try { certCollection = certs.getMatches(signer.getSID()); } catch (StoreException ex1) { System.out.println("Errore nel CertStore"); } if (certCollection.size() == 1) { X509CertificateHolder ch = (X509CertificateHolder) certCollection.toArray()[0]; try { // get Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(ch); if (debug) System.out.println(i + ") Verifiying signature from:\n" + cert.getSubjectDN()); this.signerDN = cert.getSubjectDN().toString(); if (debug) System.out.println("Certificato valido fino a " + cert.getNotAfter()); this.notBefore = df.format(cert.getNotBefore()); this.notAfter = df.format(cert.getNotAfter()); cert.checkValidity(); this.validNotExpired = true; } catch (CertificateExpiredException ex) { if (debug) System.out.println("Certificato scaduto il " + cert.getNotAfter()); } catch (CertificateNotYetValidException ex) { if (debug) System.out.println("Certificato non ancora valido. Valido da " + cert.getNotBefore()); } catch (CertificateException e) { if (debug) System.out.println("Errore Certificato "); } // VERIFICA INTEGRITA' (passando il certificato) // verify that the given certificate successfully handles // and confirms the signature associated with this signer // and, if a signingTime attribute is available, that the // certificate was valid at the time the signature was // generated. // try { // ROB: faccio solo controllo integrit -> passo solo la // chiave pubblica. if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder() .build(new X509CertificateHolder(cert.getEncoded())))) { if (debug) System.out.println("Firma " + i + " integra."); this.integrityChecked = true; } else { if (debug) System.err.println("Firma " + i + " non integra!"); } parseAuthenticatedAttributes(signer); /* * } catch (CertificateExpiredException e) { * System.out.println("Certificato per la Firma " + i + * " scaduto."); } catch (CertificateNotYetValidException e) * { System.out.println("Certificato per la Firma " + i + * " non ancora valido."); } */ } else { if (debug) System.out.println("There is not exactly one certificate for this signer!"); } i++; } } catch (CMSException e) { if (debug) System.out.println("Dati firmati non corretti: " + e.getMessage()); } catch (CertificateEncodingException e) { if (debug) System.out.println("Encoding certificato non corretto: " + e.getMessage()); } catch (OperatorCreationException e) { if (debug) System.out.println(e.getMessage()); } catch (CertificateException e) { if (debug) System.out.println("Errore nel certificato: " + e.getMessage()); } catch (IOException e) { if (debug) System.out.println(e.getMessage()); } }
From source file:it.trento.comune.j4sign.examples.CLITest.java
License:Open Source License
/** * Tests (possibly multiple) digital signatures using PKCS#11 tokens. After * correct integrity verification of all signatures, the CMS signed message * is saved on the filesystem under the users's home directory. * /* ww w .ja v a 2s.c om*/ */ public void testExternalSignature() { try { System.out.println("\n========= CMS (PKCS7) Signed message test ========\n"); System.out.print("The test message to sign is:\t"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(this.msgBytes); System.out.println(baos.toString()); System.out.print("As exadecimal string:\t\t"); System.out.println(formatAsString(this.msgBytes, " ", WRAP_AFTER)); System.out.println(); CMSProcessable msg = new CMSProcessableByteArray(this.msgBytes); // questa versione del generatore priva della classe interna // per // la generazione delle SignerInfo, che stata promossa a // classe a // s. ExternalSignatureCMSSignedDataGenerator gen = new ExternalSignatureCMSSignedDataGenerator(); // Conterr la lista dei certificati; come minimo dovr // contenere i certificati dei firmatari; opzionale, ma // consigliabile, // l'aggiunta dei certificati root per completare le catene di // certificazione. ArrayList certList = new ArrayList(); ExternalSignatureSignerInfoGenerator sig = null; String answer = "STARTVALUE"; String question = "Do you want to sign this message?"; String defaultChoice = null; int i = 0; Prompt prompt = new Prompt(); String[] choices = { "Y", "N" }; while (!answer.equals("N")) { answer = prompt.question(question, "Type Y or N:", choices, defaultChoice); if (answer.equals("Y")) { System.out.println("========================"); System.out.println("ADDING SIGNATURE " + i); if (detectCardAndCriptoki()) { System.out.println("Starting signing process."); // System.out // .println("Applying SHA1 digest with RSA // encryption."); sig = getSignerInfoGenerator(msg, this.digestAlg, this.encAlg, this.makeDigestOnToken, // digest // on // token? certList); if (sig != null) gen.addSignerInf(sig); } // if card detected question = "\nAdd another signature?"; defaultChoice = "N"; answer = "STARTVALUE"; } i++; } if (certList.size() != 0) { // Per passare i certificati al generatore li si incapsula // in un // CertStore. CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); System.out.println("Adding certificates ... "); gen.addCertificatesAndCRLs(store); // Finalmente, si pu creare il l'oggetto CMS. System.out.println("Generating CMSSignedData "); CMSSignedData s = gen.generate(msg, true); // Verifica System.out.println("\nStarting CMSSignedData verification ... "); // recupero dal CMS la lista dei certificati Store certs = s.getCertificates(); // Recupero i firmatari. SignerInformationStore signers = s.getSignerInfos(); Collection<?> c = signers.getSigners(); System.out.println(c.size() + " signers found."); Iterator it = c.iterator(); // ciclo tra tutti i firmatari i = 0; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection<?> certCollection = certs.getMatches(signer.getSID()); if (certCollection.size() == 1) { // Iterator certIt = certCollection.iterator(); // X509Certificate cert = (X509Certificate) // certIt.next(); X509CertificateHolder ch = (X509CertificateHolder) certCollection.toArray()[0]; X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(ch); System.out.println(i + ") Verifiying signature from:\n" + cert.getSubjectDN()); /* * System.out.println("Certificate follows:"); * System.out * .println("===================================="); * System.out.println(cert); * System.out.println("====================================" * ); */ if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) { System.out.println("SIGNATURE " + i + " OK!"); } else System.err.println("SIGNATURE " + i + " Failure!"); } else System.out.println("There is not exactly one certificate for this signer!"); i++; } // writing CMS file to user's home directory this.filePath = System.getProperty("user.home") + System.getProperty("file.separator") + "ciao.txt.p7m"; System.out.println("\nSAVING FILE TO: " + filePath); FileOutputStream fos = new FileOutputStream(filePath); fos.write(s.getEncoded()); fos.flush(); fos.close(); } } catch (Exception ex) { System.err.println("EXCEPTION:\n" + ex); } }
From source file:net.markenwerk.utils.mail.smime.SmimeUtil.java
License:Open Source License
/** * Checks a SMIMESigned to make sure that the signature matches. *//* w w w . jav a 2 s. co m*/ private static boolean checkSignature(SMIMESigned smimeSigned) throws MessagingException, IOException, GeneralSecurityException { try { boolean returnValue = true; @SuppressWarnings("rawtypes") Store certificates = smimeSigned.getCertificates(); Iterator<SignerInformation> signerInformations = smimeSigned.getSignerInfos().getSigners().iterator(); while (returnValue && signerInformations.hasNext()) { SignerInformation signerInformation = signerInformations.next(); X509Certificate certificate = getCertificate(certificates, signerInformation.getSID()); SignerInformationVerifier verifier = getVerifier(certificate); if (!signerInformation.verify(verifier)) { returnValue = false; } } return returnValue; } catch (Exception e) { throw handledException(e); } }
From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectParser.java
License:BSD License
private void verifySignature(X509Certificate certificate, SignerInformation signer) { String errorMessage = null;/*from www. java 2 s. c om*/ try { /* * Use the public key for the "verifier" not the certificate, because otherwise * BC will reject the CMS if the signingTime is outside of the EE certificate validity * time. This happens occasionally and is no ground to reject according to standards: * http://tools.ietf.org/html/rfc6488#section-2.1.6.4.3 */ validationResult.rejectIfFalse( signer.verify(new JcaSignerInfoVerifierBuilder(BouncyCastleUtil.DIGEST_CALCULATOR_PROVIDER) .build(certificate.getPublicKey())), SIGNATURE_VERIFICATION); } catch (OperatorCreationException e) { errorMessage = String.valueOf(e.getMessage()); } catch (CMSException e) { errorMessage = String.valueOf(e.getMessage()); } if (errorMessage != null) { validationResult.rejectIfFalse(false, SIGNATURE_VERIFICATION, errorMessage); } }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilderTest.java
License:BSD License
/** * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.6 *//*from w w w. ja v a 2 s .com*/ @Test public void shouldCmsObjectHaveValidSignature() throws Exception { Collection<?> signers = signedDataParser.getSignerInfos().getSigners(); SignerInformation signer = (SignerInformation) signers.iterator().next(); assertNotNull(signer.getSignature()); assertTrue("signature verify", signer.verify(new JcaSignerInfoVerifierBuilder(BouncyCastleUtil.DIGEST_CALCULATOR_PROVIDER) .build(ProvisioningCmsCertificateBuilderTest.TEST_CMS_CERT.getCertificate()))); }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectParser.java
License:BSD License
/** * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.6 *///from ww w.j ava2 s .c om private void verifySignature(SignerInformation signer) { String errorMessage = null; try { validationResult.rejectIfFalse( signer.verify(new JcaSignerInfoVerifierBuilder(BouncyCastleUtil.DIGEST_CALCULATOR_PROVIDER) .build(cmsCertificate)), SIGNATURE_VERIFICATION); } catch (CMSException e) { errorMessage = String.valueOf(e.getMessage()); } catch (OperatorCreationException e) { errorMessage = String.valueOf(e.getMessage()); } if (errorMessage != null) { validationResult.rejectIfFalse(false, SIGNATURE_VERIFICATION, errorMessage); } }
From source file:no.difi.oxalis.as2.util.MimeMessageHelperTest.java
License:EUPL
/** * verify the signature (assuming the cert is contained in the message) *///from ww w .java2 s. c o m private boolean verify(String resourceName, boolean debug) { System.out.println("Verifying resource " + resourceName + " (debug=" + debug + ")"); String resourcePath = "real-mdn-examples/" + resourceName; try { // shortcuts lots of steps in the above test (parseLegalMimeMessageWithHeaders) MimeMultipart multipartSigned = (MimeMultipart) MimeMessageHelper .createMimeMessage( MimeMessageHelperTest.class.getClassLoader().getResourceAsStream(resourcePath)) .getContent(); assertNotNull(multipartSigned); // verify signature SMIMESigned signedMessage = new SMIMESigned(multipartSigned); Store certs = signedMessage.getCertificates(); SignerInformationStore signers = signedMessage.getSignerInfos(); for (Object signerInformation : signers.getSigners()) { SignerInformation signer = (SignerInformation) signerInformation; Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIterator = certCollection.iterator(); X509Certificate cert = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate((X509CertificateHolder) certIterator.next()); if (debug) System.out.println("Signing certificate : " + cert); SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(cert); if (signer.verify(signerInformationVerifier)) return true; } } catch (Exception ex) { System.out.println("Verification failed with exception " + ex.getMessage()); } return false; }
From source file:no.difi.oxalis.as2.util.SMimeBC.java
License:EUPL
/** * http://stackoverflow.com/a/31557473/135001 *//*ww w.j a va 2s .c o m*/ public static X509Certificate verifySignature(Map hashes, byte[] signature) throws OxalisSecurityException, OxalisAs2InboundException { try { CMSSignedData signedData = new CMSSignedData(hashes, signature); Store store = signedData.getCertificates(); SignerInformationStore signerInformationStore = signedData.getSignerInfos(); for (SignerInformation signerInformation : signerInformationStore.getSigners()) { Collection<X509CertificateHolder> certCollection = store.getMatches(signerInformation.getSID()); Iterator<X509CertificateHolder> certificateIterator = certCollection.iterator(); if (!certificateIterator.hasNext()) throw new OxalisAs2InboundException(Disposition.AUTHENTICATION_FAILED, "Unable to find certificate in signature.", null); X509CertificateHolder certificateHolder = certificateIterator.next(); X509Certificate certificate = x509CertificateConverter.getCertificate(certificateHolder); SignerInformationVerifier verifier = getSignerInfoVerifierBuilder().build(certificate); if (signerInformation.verify(verifier)) return certificate; } throw new OxalisSecurityException("Unable to verify signature."); } catch (CMSSignerDigestMismatchException e) { throw new OxalisSecurityException("Invalid message digest.", e); } catch (CMSException | CertificateException | OperatorCreationException e) { throw new OxalisSecurityException(e.getMessage(), e); } }
From source file:org.apache.james.transport.KeyStoreHolder.java
License:Apache License
/** * Verifies the signature of a SMIME message. * /*from w w w. j a va2s . c o m*/ * It checks also if the signer's certificate is trusted using the loaded * keystore as trusted certificate store. * * @param signed * the signed mail to check. * @return a list of SMIMESignerInfo which keeps the data of each mail * signer. * @throws Exception * @throws MessagingException */ public List<SMIMESignerInfo> verifySignatures(SMIMESigned signed) throws Exception { CertStore certs = new JcaCertStoreBuilder().addCertificates(signed.getCertificates()) .addCRLs(signed.getCRLs()).build(); SignerInformationStore siginfo = signed.getSignerInfos(); Collection<SignerInformation> sigCol = siginfo.getSigners(); List<SMIMESignerInfo> result = new ArrayList<SMIMESignerInfo>(sigCol.size()); // I iterate over the signer collection // checking if the signatures put // on the message are valid. for (SignerInformation info : sigCol) { // I get the signer's certificate X509CertificateHolderSelector x509CertificateHolderSelector = new X509CertificateHolderSelector( info.getSID().getSubjectKeyIdentifier()); X509CertSelector certSelector = new JcaX509CertSelectorConverter() .getCertSelector(x509CertificateHolderSelector); @SuppressWarnings("unchecked") Collection<X509Certificate> certCollection = (Collection<X509Certificate>) certs .getCertificates(certSelector); if (!certCollection.isEmpty()) { X509Certificate signerCert = certCollection.iterator().next(); // The issuer's certifcate is searched in the list of trusted certificate. CertPath path = verifyCertificate(signerCert, certs, keyStore); try { // if the signature is valid the SMIMESignedInfo is // created using "true" as last argument. If it is // invalid an exception is thrown by the "verify" method // and the SMIMESignerInfo is created with "false". // // The second argument "path" is not null if the // certificate can be trusted (it can be connected // by a chain of trust to a trusted certificate), null // otherwise. if (info.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(signerCert))) { result.add(new SMIMESignerInfo(signerCert, path, true)); } } catch (Exception e) { result.add(new SMIMESignerInfo(signerCert, path, false)); } } } return result; }
From source file:org.apache.jmeter.assertions.SMIMEAssertion.java
License:Apache License
private static AssertionResult verifySignature(SMIMEAssertionTestElement testElement, SMIMESignedParser s, String name) throws CMSException { AssertionResult res = new AssertionResult(name); try {// w w w . ja v a2 s. c om Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Iterator<?> signerIt = signers.getSigners().iterator(); if (signerIt.hasNext()) { SignerInformation signer = (SignerInformation) signerIt.next(); Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator(); if (certIt.hasNext()) { // the signer certificate X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); if (testElement.isVerifySignature()) { SignerInformationVerifier verifier = null; try { verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert); } catch (OperatorCreationException e) { log.error("Can't create a provider", e); } if (verifier == null || !signer.verify(verifier)) { res.setFailure(true); res.setFailureMessage("Signature is invalid"); } } if (testElement.isSignerCheckConstraints()) { StringBuilder failureMessage = new StringBuilder(); String serial = testElement.getSignerSerial(); if (!JOrphanUtils.isBlank(serial)) { BigInteger serialNbr = readSerialNumber(serial); if (!serialNbr.equals(cert.getSerialNumber())) { res.setFailure(true); failureMessage.append("Serial number ").append(serialNbr) .append(" does not match serial from signer certificate: ") .append(cert.getSerialNumber()).append("\n"); } } String email = testElement.getSignerEmail(); if (!JOrphanUtils.isBlank(email)) { List<String> emailFromCert = getEmailFromCert(cert); if (!emailFromCert.contains(email)) { res.setFailure(true); failureMessage.append("Email address \"").append(email) .append("\" not present in signer certificate\n"); } } String subject = testElement.getSignerDn(); if (subject.length() > 0) { final X500Name certPrincipal = cert.getSubject(); log.debug("DN from cert: " + certPrincipal.toString()); X500Name principal = new X500Name(subject); log.debug("DN from assertion: " + principal.toString()); if (!principal.equals(certPrincipal)) { res.setFailure(true); failureMessage.append("Distinguished name of signer certificate does not match \"") .append(subject).append("\"\n"); } } String issuer = testElement.getIssuerDn(); if (issuer.length() > 0) { final X500Name issuerX500Name = cert.getIssuer(); log.debug("IssuerDN from cert: " + issuerX500Name.toString()); X500Name principal = new X500Name(issuer); log.debug("IssuerDN from assertion: " + principal); if (!principal.equals(issuerX500Name)) { res.setFailure(true); failureMessage .append("Issuer distinguished name of signer certificate does not match \"") .append(subject).append("\"\n"); } } if (failureMessage.length() > 0) { res.setFailureMessage(failureMessage.toString()); } } if (testElement.isSignerCheckByFile()) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CertificateHolder certFromFile; InputStream inStream = null; try { inStream = new BufferedInputStream( new FileInputStream(testElement.getSignerCertFile())); certFromFile = new JcaX509CertificateHolder( (X509Certificate) cf.generateCertificate(inStream)); } finally { IOUtils.closeQuietly(inStream); } if (!certFromFile.equals(cert)) { res.setFailure(true); res.setFailureMessage("Signer certificate does not match certificate " + testElement.getSignerCertFile()); } } } else { res.setFailure(true); res.setFailureMessage("No signer certificate found in signature"); } } // TODO support multiple signers if (signerIt.hasNext()) { log.warn("SMIME message contains multiple signers! Checking multiple signers is not supported."); } } catch (GeneralSecurityException e) { log.error(e.getMessage(), e); res.setError(true); res.setFailureMessage(e.getMessage()); } catch (FileNotFoundException e) { res.setFailure(true); res.setFailureMessage("certificate file not found: " + e.getMessage()); } return res; }