List of usage examples for org.bouncycastle.mail.smime SMIMESigned SMIMESigned
public SMIMESigned(Part message) throws MessagingException, CMSException, SMIMEException
From source file:br.ufpb.dicomflow.integrationAPI.mail.impl.SMTPServiceExtractor.java
License:Open Source License
private boolean checkSignature(MimeMultipart content, X509Certificate cert) throws OperatorCreationException, MessagingException, CMSException, IOException, SMIMEException, Exception { for (int i = 0; i < content.getCount(); i++) { Part part = content.getBodyPart(i); String contentType = part.getContentType(); if (contentType.toLowerCase().startsWith("multipart/signed") || contentType.toLowerCase().startsWith("application/pkcs7-mime") || contentType.toLowerCase().startsWith("application/x-pkcs7-mime") || contentType.toLowerCase().startsWith("application/pkcs7-signature")) { ////from w w w . j a v a 2 s . co m // in this case the content is wrapped in the signature block. // SMIMESigned s = new SMIMESigned(content); return verify(s); } } return false; }
From source file:chapter9.EnvelopedSignedMailExample.java
/** * * @param args//from w ww . j a va2 s .co m * @throws Exception */ public static void main(String[] args) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); CertStore certsAndCRLs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain)), CryptoDefs.Provider.BC.getName()); X509Certificate cert = (X509Certificate) chain[0]; //1.- Create the message we want signed MimeBodyPart dataPart = new MimeBodyPart(); dataPart.setText("Hello World!!"); //2.- Create the signed message MimeMultipart signedMulti = SignedMailExample.createMultipartWithSignature(key, cert, certsAndCRLs, dataPart); //3.- Create the body part containing the signed message MimeBodyPart signedPart = new MimeBodyPart(); signedPart.setContent(signedMulti); //4.- Set up the generator SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(cert); //5.- Generate the enveloped message MimeBodyPart envPart = gen.generate(signedPart, SMIMEEnvelopedGenerator.AES256_CBC, CryptoDefs.Provider.BC.getName()); //6.- Create the mail message MimeMessage mail = Utils.createMimeMessage("example signed and enveloped message", envPart.getContent(), envPart.getContentType()); //7.- Create the enveloped object from the mail message SMIMEEnveloped enveloped = new SMIMEEnveloped(mail); //8.- Look for our recipient identifier RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()), cert.getSerialNumber()); RecipientInformationStore recipients = enveloped.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); //9.- Decryption step MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(key, CryptoDefs.Provider.BC.getName())); //10.- Extract the multipart from the body part if (res.getContent() instanceof MimeMultipart) { SMIMESigned signed = new SMIMESigned((MimeMultipart) res.getContent()); //11.- Verification step X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS); if (isValid(signed, rootCert)) System.out.println("\t verification succeeded!!"); else System.out.println("\t verification failed!!"); //12.- Content display step MimeBodyPart content = signed.getContent(); System.out.print("\t Content: "); System.out.println(content.getContent()); } else System.out.println("\t wrong content found!!"); }
From source file:chapter9.SignedMailExample.java
/** * * @param args//ww w . jav a 2 s .c om * @throws Exception */ public static void main(String[] args) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); CertStore certsAndCRLs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain)), CryptoDefs.Provider.BC.getName()); X509Certificate cert = (X509Certificate) chain[0]; //1.- Create the message we want signed MimeBodyPart dataPart = new MimeBodyPart(); dataPart.setText("Hello World!!"); //2.- Create the signed message MimeMultipart multiPart = createMultipartWithSignature(key, cert, certsAndCRLs, dataPart); //3.- Create the mail message MimeMessage mail = Utils.createMimeMessage("example signed message", multiPart, multiPart.getContentType()); //4.- Extract the message from the mail message if (mail.isMimeType("multipart/signed")) { SMIMESigned signed = new SMIMESigned((MimeMultipart) mail.getContent()); //5.- Verification step X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS); if (isValid(signed, rootCert)) System.out.println("\t verification succeeded!!"); else System.out.println("\t verification failed!!"); //6.- Content display step MimeBodyPart content = signed.getContent(); System.out.print("\t Content: "); System.out.println(content.getContent()); } else System.out.println("\t wrong content found!!"); }
From source file:com.cordys.coe.ac.emailio.util.smime.SMIMEUtil.java
License:Apache License
/** * This method validates the signature for the bodypart. * * @param mbpSigned mmFinal The message to validate the signature. * * @throws EmailIOException In case of any exceptions. *///ww w . j av a2 s . c o m public static void validateSignature(MimePart mbpSigned) throws EmailIOException { try { if (mbpSigned.isMimeType("multipart/signed")) { SMIMESigned s = new SMIMESigned((MimeMultipart) mbpSigned.getContent()); verify(s); } else if (mbpSigned.isMimeType("application/pkcs7-mime") || mbpSigned.isMimeType("application/x-pkcs7-mime")) { // in this case the content is wrapped in the signature block. SMIMESigned s = new SMIMESigned(mbpSigned); verify(s); } } catch (EmailIOException eioe) { throw eioe; } catch (Exception e) { throw new EmailIOException(e, EmailIOExceptionMessages.EIOE_COULD_NOT_VALIDATE_SIGNATURE); } if (LOG.isDebugEnabled()) { LOG.debug("Signature is valid"); } }
From source file:com.cordys.coe.test.smime.TestSMIMEBouncyCastle.java
License:Apache License
/** * DOCUMENTME.//from w w w.ja v a2 s.com * * @param res * * @throws Exception DOCUMENTME */ private void doSignatureValidation(MimeBodyPart res) throws Exception { if (res.isMimeType("multipart/signed")) { SMIMESigned s = new SMIMESigned((MimeMultipart) res.getContent()); // // extract the content // MimeBodyPart content = s.getContent(); System.out.println("Content:"); Object cont = content.getContent(); if (cont instanceof String) { System.out.println((String) cont); } else if (cont instanceof Multipart) { System.out.println(MailMessageUtil.dumpMultipart("", (Multipart) cont)); } System.out.println("Status:"); verify(s); } else if (res.isMimeType("application/pkcs7-mime") || res.isMimeType("application/x-pkcs7-mime")) { // // in this case the content is wrapped in the signature block. // SMIMESigned s = new SMIMESigned(res); // // extract the content // MimeBodyPart content = s.getContent(); System.out.println("Content:"); Object cont = content.getContent(); if (cont instanceof String) { System.out.println((String) cont); } else if (cont instanceof Multipart) { System.out.println(MailMessageUtil.dumpMultipart("", (Multipart) cont)); } System.out.println("Status:"); verify(s); } else { System.err.println("Not a signed message!"); } }
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
/** * @param mp//from w ww.ja v a 2s. co m * @param certs * @param cte * @return * @throws MessagingException * @throws GeneralSecurityException * @throws IOException * @throws CertificateEncodingException */ public static Tuple verifySmimeDigSig(Multipart mp, Certificate[] certs, String cte) throws MessagingException, GeneralSecurityException, IOException, CertificateEncodingException { tstArgIsType("multipart", mp, MimeMultipart.class); tstObjArg("certs", certs); MimeMultipart mmp = (MimeMultipart) mp; SMIMESigned sc; SignerInformation si; byte[] digest = null; try { sc = isEmpty(cte) ? new SMIMESigned(mmp) : new SMIMESigned(mmp, cte); } catch (CMSException e) { throw new GeneralSecurityException(e); } Provider prov = Crypto.getInstance().getProvider(); Store s = new JcaCertStore(asList(true, certs)); Collection<?> c; JcaSimpleSignerInfoVerifierBuilder bdr; for (Object obj : sc.getSignerInfos().getSigners()) try { si = (SignerInformation) obj; c = s.getMatches(si.getSID()); for (Iterator<?> it = c.iterator(); it.hasNext();) { bdr = new JcaSimpleSignerInfoVerifierBuilder().setProvider(prov); if (si.verify(bdr.build((X509CertificateHolder) it.next()))) { digest = si.getContentDigest(); break; } } if (digest != null) { break; } } catch (Exception e) { } if (digest == null) { throw new GeneralSecurityException("Failed to verify signature: no matching certificate"); } //else return new Tuple(sc.getContentAsMimeMessage(newSession()).getContent(), digest); }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * Returns the digest OID algorithm from a signature that signes the passed * message part The return value for sha1 is e.g. "1.3.14.3.2.26". *//*w ww . ja va 2 s . c o m*/ public String getDigestAlgOIDFromSignature(Part part) throws Exception { if (part == null) { throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Part is absent"); } if (part.isMimeType("multipart/signed")) { MimeMultipart signedMultiPart = null; if (part.getContent() instanceof MimeMultipart) { signedMultiPart = (MimeMultipart) part.getContent(); } else { //assuming it is an inputstream now signedMultiPart = new MimeMultipart( new ByteArrayDataSource((InputStream) part.getContent(), part.getContentType())); } SMIMESigned signed = new SMIMESigned(signedMultiPart); SignerInformationStore signerStore = signed.getSignerInfos(); Iterator iterator = signerStore.getSigners().iterator(); while (iterator.hasNext()) { SignerInformation signerInfo = (SignerInformation) iterator.next(); return (signerInfo.getDigestAlgOID()); } throw new GeneralSecurityException( "getDigestAlgOIDFromSignature: Unable to identify signature algorithm."); } throw new GeneralSecurityException("Content-Type indicates data isn't signed"); }
From source file:eu.peppol.as2.MimeMessageHelperTest.java
License:EUPL
/** * verify the signature (assuming the cert is contained in the message) *///from www . j a v a 2 s.co m private boolean verify(String resourceName, boolean debug) { System.out.println("Verifying resource " + resourceName + " (debug=" + debug + ")"); String resourcePath = "real-mdn-examples/" + resourceName; try { // add provider Security.addProvider(new BouncyCastleProvider()); // 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(new BouncyCastleProvider()) .getCertificate((X509CertificateHolder) certIterator.next()); if (debug) System.out.println("Signing certificate : " + cert); SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .setProvider(new BouncyCastleProvider()).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:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java
License:Open Source License
@Test public void testSignedAS2Message() throws Exception { InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG); ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins)); partnershipDVO.setIsOutboundSignRequired(true); String mid = RANDOM.toString(); AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG)); //Verify As2Signing Message try {/*w w w .jav a 2s .co m*/ SMIMESigned signed = new SMIMESigned((MimeMultipart) as2Msg.getBodyPart().getContent()); SignerInformationStore signers = signed.getSignerInfos(); Iterator signerInfos = signers.getSigners().iterator(); while (signerInfos.hasNext()) { SignerInformation signerInfo = (SignerInformation) signerInfos.next(); if (!signerInfo.verify(partnershipDVO.getEffectiveVerifyCertificate(), "BC")) { Assert.fail("Signature Verfifcation Failed"); } } //Assert the filename value MimeBodyPart signedPart = signed.getContent(); String filenameHdr = signedPart.getHeader("Content-Disposition")[0]; Assert.assertEquals("Lost Filename Header Information", MOCK_AS2_MSG, getFileName(filenameHdr)); // Verify MIC Value ByteArrayOutputStream baos = new ByteArrayOutputStream(); signedPart.writeTo(baos); byte[] content = (baos.toByteArray()); String mic = calculateMIC(content); MessageDVO msgDVO = getStoredMessage(mid); Assert.assertEquals("MIC Value is not valid.", mic, msgDVO.getMicValue()); } catch (Exception exp) { Assert.fail("Signature Verfifcation Failed"); } Assert.assertTrue(true); }
From source file:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java
License:Open Source License
@Test public void testSignedEncryptedAS2Message() throws Exception { InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG); ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins)); // Prepare Data String mid = RANDOM.toString(); partnershipDVO.setIsOutboundEncryptRequired(true); partnershipDVO.setIsOutboundSignRequired(true); //Encrypt message AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG)); // Decrypt Message SMIMEEnveloped crypted = new SMIMEEnveloped(as2Msg.getBodyPart()); RecipientId recId = new RecipientId(); recId.setSerialNumber(partnershipDVO.getEncryptX509Certificate().getSerialNumber()); recId.setIssuer(partnershipDVO.getEncryptX509Certificate().getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = crypted.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); KeyStoreManager keyMan = (KeyStoreManager) TARGET.getSystemModule().getComponent("keystore-manager"); MimeBodyPart decrpted = SMIMEUtil.toMimeBodyPart(recipient.getContent(keyMan.getPrivateKey(), "BC")); //Verify Signature try {/*w ww. j ava 2 s . c om*/ SMIMESigned signed = new SMIMESigned((MimeMultipart) decrpted.getContent()); SignerInformationStore signers = signed.getSignerInfos(); Iterator signerInfos = signers.getSigners().iterator(); while (signerInfos.hasNext()) { SignerInformation signerInfo = (SignerInformation) signerInfos.next(); if (!signerInfo.verify(partnershipDVO.getEffectiveVerifyCertificate(), "BC")) { Assert.fail("Signature Verfifcation Failed"); } } //Assert the filename value MimeBodyPart signedPart = signed.getContent(); String filenameHdr = signedPart.getHeader("Content-Disposition")[0]; Assert.assertEquals("Lost Filename Header Information", MOCK_AS2_MSG, getFileName(filenameHdr)); // Verify MIC Value ByteArrayOutputStream baos = new ByteArrayOutputStream(); signedPart.writeTo(baos); byte[] content = (baos.toByteArray()); String mic = calculateMIC(content); MessageDVO msgDVO = getStoredMessage(mid); Assert.assertEquals("MIC Value is not valid.", mic, msgDVO.getMicValue()); } catch (Exception exp) { Assert.fail("Signature Verfifcation Failed"); } Assert.assertTrue(true); }