List of usage examples for org.bouncycastle.mail.smime SMIMEEnveloped SMIMEEnveloped
public SMIMEEnveloped(MimeMessage message) throws MessagingException, CMSException
From source file:br.ufpb.dicomflow.integrationAPI.mail.impl.SMTPServiceExtractor.java
License:Open Source License
private Multipart getDecryptedContent(Message message, X509Certificate signCert, X509Certificate encryptCert, PrivateKey privateKey) throws OperatorCreationException, Exception { RecipientId recId = new JceKeyTransRecipientId(encryptCert); SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = SMIMEUtil/*from w w w . j a v a 2s. c o m*/ .toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(privateKey))); MimeMultipart content = (MimeMultipart) res.getContent(); Multipart decryptedContent = null; if (checkSignature(content, signCert)) { for (int i = 0; i < content.getCount(); i++) { Part part = content.getBodyPart(i); String contentType = part.getContentType(); if (contentType.toLowerCase().startsWith("multipart/mixed")) { decryptedContent = (Multipart) part.getContent(); } } } return decryptedContent; }
From source file:chapter9.EnvelopedMailExample.java
/** * * @param args/*from w w w . jav a2s .c o 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); X509Certificate cert = (X509Certificate) chain[0]; //1.- Create the message we want encrypted MimeBodyPart dataPart = new MimeBodyPart(); dataPart.setText("Hello World!!"); //2.- Set up the generator SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(cert); //3.- Generate the enveloped message MimeBodyPart envPart = gen.generate(dataPart, SMIMEEnvelopedGenerator.AES256_CBC, CryptoDefs.Provider.BC.getName()); //4.- Create the mail message MimeMessage mail = Utils.createMimeMessage("example enveloped message", envPart.getContent(), envPart.getContentType()); //5.- Create the enveloped object from the mail message SMIMEEnveloped enveloped = new SMIMEEnveloped(mail); //6.- 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); if (recipient != null) { //7.- Decryption step MimeBodyPart recoveredPart = SMIMEUtil .toMimeBodyPart(recipient.getContent(key, CryptoDefs.Provider.BC.getName())); //8.- Content display step System.out.print("\t Content:"); System.out.println(recoveredPart.getContent()); } else System.out.println("\t could not find a matching recipient!!"); }
From source file:chapter9.EnvelopedSignedMailExample.java
/** * * @param args//from w ww .ja va 2 s.c o 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:com.cordys.coe.ac.emailio.util.smime.SMIMEUtil.java
License:Apache License
/** * This method will decrypt the source message and return the decrypted version of the mail. * * @param mmSource The message to decrypt. * @param scConfig The S/MIME configuration details. * * @return The decrypted message./*from w w w . j av a2 s . co m*/ * * @throws EmailIOException In case of any exceptions. */ public static MimeMessage decryptMessage(MimeMessage mmSource, ISMIMEConfiguration scConfig) throws EmailIOException { MimeMessage mmReturn = null; // First we create the wrapper around the encrypted message try { SMIMEEnveloped seSMIME = new SMIMEEnveloped(mmSource); // Now get all recipients for this mail and try to find the matching certificate with // the private key. RecipientInformationStore recipients = seSMIME.getRecipientInfos(); ICertificateInfo ciInfo = null; RecipientInformation riInfo = null; Collection<?> cRecipients = recipients.getRecipients(); for (Iterator<?> iRecipients = cRecipients.iterator(); iRecipients.hasNext();) { riInfo = (RecipientInformation) iRecipients.next(); // Figure out if we have a key for this recipient ID. ciInfo = scConfig.getCertificateInfo(riInfo.getRID()); if (ciInfo != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found certificate info for RID " + riInfo.getRID()); } break; } } // Check if we found all information. if (ciInfo == null) { throw new EmailIOException( EmailIOExceptionMessages.EIOE_COULD_NOT_FIND_ANY_CERTIFICATE_INFORMATION_FOR_ANY_OF_THE_RECIPIENTS); } if (riInfo == null) { throw new EmailIOException( EmailIOExceptionMessages.EIOE_COULD_NOT_DECRYPT_MESSAGE_BECAUSE_NO_RECIPIENT_INFORMATION_WAS_FOUND); } // We have all the necessary information, so now we can really decrypt the message. Key kPrivate = ciInfo.getKey(); if (kPrivate == null) { throw new EmailIOException( EmailIOExceptionMessages.EIOE_COULD_NOT_FIND_A_PRIVATE_KEY_FOR_RECIPIENT_0, riInfo.getRID().getSubjectAsString()); } // Do the actual decrypting of the content. MimeBodyPart res = org.bouncycastle.mail.smime.SMIMEUtil .toMimeBodyPart(riInfo.getContent(kPrivate, "BC")); // Now create a decrypted version of the mail. mmReturn = new MimeMessage(mmSource); MimeMultipart mmTemp = new MimeMultipart(); mmTemp.addBodyPart(res); mmReturn.setContent(mmTemp); mmReturn.saveChanges(); if (LOG.isDebugEnabled()) { LOG.debug( "The message was now decrypted. Returning mail:\n" + MailMessageUtil.rawMessage(mmReturn)); } } catch (EmailIOException eioe) { throw eioe; } catch (Exception e) { throw new EmailIOException(e, EmailIOExceptionMessages.EIOE_ERROR_DECRYPTING_EMAIL_MESSAGE); } return mmReturn; }
From source file:com.cordys.coe.test.smime.TestSMIMEBouncyCastle.java
License:Apache License
/** * Test to fetch e-mails from a POP3 mainbox. * * @throws Exception/*from w ww .j a v a2 s . com*/ */ public void fetchAllMessage() throws Exception { int config = 0; try { config = DOC .parseString("<emailboxes xmlns=\"http://emailioconnector.coe.cordys.com/2.0/configuration\">" + "<emailbox>" + "<name>testmailbox</name>" + "<host>srv-nl-ces70</host>" + "<port>110</port>" + "<type>POP3</type>" + "<username>cordystestuser1</username>" + "<password>Y29yZHlzdGVzdHVzZXIx</password>" + "<pollinterval>5000</pollinterval>" + "<folders>" + "<folder>Inbox</folder>" + "</folders>" + "</emailbox>" + "</emailboxes>"); int emailBoxConfigNode = Node.getFirstElement(config); IEmailBox e = new POP3EmailBox(emailBoxConfigNode, 0, "", true); IEmailConnection ec = EmailConnectionFactory.createConnection(e); Message[] am = ec.getEmailHeaders(); for (int iCount = 0; iCount < am.length; iCount++) { MimeMessage msg = (MimeMessage) am[iCount]; if (LOG.isEnabled(Severity.DEBUG)) { LOG.log(Severity.DEBUG, "= Message " + (iCount + 1) + " ="); LOG.log(Severity.DEBUG, msg.getSubject() + " from " + msg.getFrom()[0].toString() + " to " + msg.getRecipients(RecipientType.TO)[0].toString()); } // TODO: We need to detect whether or not the mail is encrypted/signed. To do this // we need to example the content type of the mail. // We need to figure out which certificate to use for receiving the mail. We'll go // through all known identities to see if we're there. Map<String, ICertificateInfo> identities = m_km.getIdentities(); // Parse the mail message SMIMEEnveloped m = new SMIMEEnveloped(msg); // Find the details of a receipient that can decrypt the message. RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = null; ICertificateInfo certInfo = null; for (ICertificateInfo tmp : identities.values()) { recipient = recipients.get(tmp.getRecipientId()); if (recipient != null) { certInfo = tmp; System.out.println( "Found a recipient: " + certInfo.getAlias() + "/" + certInfo.getEmailAddress()); break; } } // Now do the actual decryption of the message. Key privateKey = certInfo.getKey(); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(privateKey, "BC")); // Do the signature doSignatureValidation(res); // So now the mail is decrypted. If it's signed we also do the signature check. Once // that's done we create a NEW dummy MimeMessage which is identical to the original // mail, but with the Encrypted part removed. MimeMessage mmNew = new MimeMessage(msg); MimeMultipart mmTemp = new MimeMultipart(); mmTemp.addBodyPart(res); mmNew.setContent(mmTemp); mmNew.saveChanges(); // The part will be a stream. And the stream contains a mail message. if (res != null) { LOG.log(Severity.DEBUG, "= Decrypted message " + (iCount + 1)); LOG.log(Severity.DEBUG, "==============================="); LOG.log(Severity.DEBUG, MailMessageUtil.dumpMessage(mmNew)); LOG.log(Severity.DEBUG, "==============================="); LOG.log(Severity.DEBUG, "Original raw:\n" + MailMessageUtil.rawMessage(msg) + "\n\n\nDecrypted raw:\n" + MailMessageUtil.rawMessage(mmNew)); } else { System.out.println("failed to decrypt message."); } } } finally { if (config > 0) { Node.delete(config); } } }
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
/** * @param key/* ww w. j a v a 2s . c o m*/ * @param part * @return * @throws MessagingException * @throws GeneralSecurityException * @throws IOException */ public static StreamData smimeDecrypt(PrivateKey key, BodyPart part) throws MessagingException, GeneralSecurityException, IOException { tstArgIsType("bodypart", part, MimeBodyPart.class); tstObjArg("private-key", key); CMSTypedStream cms = null; try { SMIMEEnveloped env = new SMIMEEnveloped((MimeBodyPart) part); cms = smime_decrypt(key, env); } catch (CMSException e) { throw new GeneralSecurityException(e); } if (cms == null) { throw new GeneralSecurityException("Failed to decrypt: no matching decryption key"); } //else return readStream(cms.getContentStream()); }
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
/** * @param keys/*ww w. ja v a2 s . co m*/ * @param msg * @return * @throws GeneralSecurityException * @throws MessagingException * @throws IOException */ public static StreamData smimeDecryptAsStream(PrivateKey[] keys, MimeMessage msg) throws GeneralSecurityException, MessagingException, IOException { tstObjArg("mime-message", msg); tstObjArg("private-key(s)", keys); CMSTypedStream cms = null; SMIMEEnveloped env; try { env = new SMIMEEnveloped(msg); } catch (CMSException e) { throw new GeneralSecurityException(e); } for (int n = 0; n < keys.length; ++n) { cms = smime_decrypt(keys[n], env); if (cms != null) { break; } cms = null; } if (cms == null) { throw new GeneralSecurityException("Failed to decrypt: no matching decryption key"); } //else return readStream(cms.getContentStream()); }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/** * Decrypts the data of a message with all given certificates etc * * @param info MessageInfo, the encryption algorith will be stored in the * encryption type of this info/*w w w.j a va2 s. c om*/ * @param rawMessageData encrypted data, will be decrypted * @param contentType contentType of the data * @param privateKey receivers private key * @param certificate receivers certificate */ public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver, X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception { AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info(); MimeBodyPart encryptedBody = new MimeBodyPart(); encryptedBody.setHeader("content-type", contentType); encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType))); JceKeyTransRecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver); SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody); BCCryptoHelper helper = new BCCryptoHelper(); String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID()); if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) { info.setEncryptionType(AS2Message.ENCRYPTION_3DES); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) { info.setEncryptionType(AS2Message.ENCRYPTION_DES); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) { info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_128); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_192); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_256); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) { info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN); } else { info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM); } RecipientInformationStore recipients = enveloped.getRecipientInfos(); enveloped = null; encryptedBody = null; RecipientInformation recipient = recipients.get(recipientId); if (recipient == null) { //give some details about the required and used cert for the decryption Collection recipientList = recipients.getRecipients(); Iterator iterator = recipientList.iterator(); while (iterator.hasNext()) { RecipientInformation recipientInfo = (RecipientInformation) iterator.next(); if (this.logger != null) { this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.inforequired", new Object[] { info.getMessageId(), ((KeyTransRecipientId) recipientInfo.getRID()).getIssuer() + ", " + ((KeyTransRecipientId) recipientInfo.getRID()).getSerialNumber() }), info); } } if (this.logger != null) { this.logger.log( Level.SEVERE, this.rb .getResourceString("decryption.infoassigned", new Object[] { info.getMessageId(), receiverCryptAlias, recipientId.getIssuer() + ", " + recipientId.getSerialNumber() }), info); } throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR, "Error decrypting the message: Recipient certificate does not match.", message); } //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses //far more memory. InputStream contentStream = recipient .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC")) .getContentStream(); //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream(); //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_", ".mem", null); this.copyStreams(contentStream, decryptedOutput); decryptedOutput.flush(); decryptedOutput.close(); contentStream.close(); byte[] decryptedData = null; //size of the data was < than the threshold if (decryptedOutput.isInMemory()) { decryptedData = decryptedOutput.getData(); } else { //data has been written to a temp file: reread and return ByteArrayOutputStream memOut = new ByteArrayOutputStream(); decryptedOutput.writeTo(memOut); memOut.flush(); memOut.close(); //finally delete the temp file boolean deleted = decryptedOutput.getFile().delete(); decryptedData = memOut.toByteArray(); } if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("decryption.done.alias", new Object[] { info.getMessageId(), receiverCryptAlias, this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }), info); } return (decryptedData); }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * Used for mendelson rosettaNet// w w w . j a va 2 s . c om */ public MimeBodyPart decrypt(MimeBodyPart part, Certificate cert, Key key) throws GeneralSecurityException, MessagingException, CMSException, IOException, SMIMEException { if (!this.isEncrypted(part)) { throw new GeneralSecurityException( "decrypt: Unable to decrypt - Content-Type indicates data isn't encrypted"); } X509Certificate x509Cert = castCertificate(cert); SMIMEEnveloped envelope = new SMIMEEnveloped(part); RecipientId recipientId = new JceKeyTransRecipientId(x509Cert); RecipientInformation recipient = envelope.getRecipientInfos().get(recipientId); if (recipient == null) { throw new GeneralSecurityException( "decrypt: Unable to decrypt data - wrong key used to decrypt the data."); } else { MimeBodyPart bodyPart = SMIMEUtil.toMimeBodyPart(recipient.getContentStream( new JceKeyTransEnvelopedRecipient(this.getPrivateKey(key)).setProvider("BC"))); return (bodyPart); } }
From source file:gov.nih.nci.cacis.nav.DecryptMail.java
License:BSD License
/** * Decrypts the encrypted MimeMessage based on supplied key * /* w w w.ja v a 2 s. c o m*/ * @param msg - encrypte MimeMessage * @param keystorepath - keystore to be used * @param storepass - keystore password (same as key) * @param keyAlias - alias for the key to be used * @return - Decrypted MimeBodyPart * @throws Exception - exception thrown, if any */ public MimeBodyPart decrypt(MimeMessage msg, String keystorepath, String storepass, String keyAlias) throws Exception { // NOPMD // // Open the key store // final KeyStore ks = KeyStore.getInstance(STORE_TYPE, PROVIDER_TYPE); // final InputStream is = getClass().getClassLoader().getResourceAsStream(keystorePath); final InputStream is = new FileInputStream(keystorepath); ks.load(is, storepass.toCharArray()); // // find the certificate for the private key and generate a // suitable recipient identifier. // final X509Certificate cert = (X509Certificate) ks.getCertificate(keyAlias); final RecipientId recId = new RecipientId(); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); final SMIMEEnveloped m = new SMIMEEnveloped(msg); final RecipientInformationStore recipients = m.getRecipientInfos(); final RecipientInformation recipient = recipients.get(recId); final MimeBodyPart res = SMIMEUtil .toMimeBodyPart(recipient.getContent(ks.getKey(keyAlias, null), PROVIDER_TYPE)); LOG.debug("Message Contents"); LOG.debug("----------------"); LOG.debug(res.getContent()); return res; }