List of usage examples for org.bouncycastle.mail.smime SMIMEEnvelopedGenerator SMIMEEnvelopedGenerator
public SMIMEEnvelopedGenerator()
From source file:br.ufpb.dicomflow.integrationAPI.mail.AbstractMailSender.java
License:Open Source License
private Message signAndEcrypt(Message message, X509Certificate signCert, X509Certificate encryptCert, PrivateKey privateKey) throws Exception { MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mailcap.addMailcap(/* www .j a v a 2 s. c o m*/ "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); mailcap.addMailcap( "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); mailcap.addMailcap( "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); mailcap.addMailcap( "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); mailcap.addMailcap( "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(mailcap); /* Create the Signer - SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X500Name(((X509Certificate) signCert).getIssuerDN().getName()), ((X509Certificate) signCert).getSerialNumber()))); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder() .setSignedAttributeGenerator(new AttributeTable(attributes)) .build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey, signCert)); /* Add the list of certs to the generator */ List certList = new ArrayList(); certList.add(signCert); Store certs = new JcaCertStore(certList); signer.addCertificates(certs); /* Sign the message */ MimeMultipart mm = signer.generate((MimeMessage) message); MimeMessage signedMessage = new MimeMessage(message.getSession()); /* Set all original MIME headers in the signed message */ Enumeration headers = ((MimeMessage) message).getAllHeaderLines(); while (headers.hasMoreElements()) { signedMessage.addHeaderLine((String) headers.nextElement()); } /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); /* Create the encrypter - SMIMEEnvelopedGenerator */ SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(encryptCert)); /* Encrypt the message */ MimeBodyPart encryptedPart = encrypter.generate(signedMessage, new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).build()); /* * Create a new MimeMessage that contains the encrypted and signed * content */ ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); MimeMessage encryptedMessage = new MimeMessage(message.getSession(), new ByteArrayInputStream(out.toByteArray())); /* Set all original MIME headers in the encrypted message */ headers = ((MimeMessage) message).getAllHeaderLines(); while (headers.hasMoreElements()) { String headerLine = (String) headers.nextElement(); /* * Make sure not to override any content-* headers from the * original message */ if (!Strings.toLowerCase(headerLine).startsWith("content-")) { encryptedMessage.addHeaderLine(headerLine); } } return encryptedMessage; }
From source file:chapter9.EnvelopedMailExample.java
/** * * @param args// www . j a 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); 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 w w . ja va 2s.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.outbound.EmailMessageFactory.java
License:Apache License
/** * This method encrypt the given email using the public keys for all senders. * * @param lMessages The list to add all individual messages to. * @param mmMessage The message to encrypt. * @param eicConfiguration The configuration of the connector. * @param sSession The JavaMail session to use. * * @throws OutboundEmailException In case of any exceptions. *//*ww w. j av a2 s . c om*/ private static void encryptMessage(List<MimeMessage> lMessages, MimeMessage mmMessage, ISMIMEConfiguration eicConfiguration, Session sSession) throws OutboundEmailException { // Create the encrypter object SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); try { // Add the public keys of all receivers to the encrypter. Address[] aaAdresses = mmMessage.getAllRecipients(); for (Address address : aaAdresses) { InternetAddress ia = (InternetAddress) address; // Find the public key for the given email address. ICertificateInfo ciRecipient = eicConfiguration.getCertificateInfo(ia.getAddress()); if ((ciRecipient == null) && !eicConfiguration.getBypassSMIME()) { throw new OutboundEmailException( OutboundEmailExceptionMessages.OEE_COULD_NOT_FIND_THE_PUBLIC_KEY_FOR_THE_EMAIL_ADDRESS_0, ia.toString()); } if (ciRecipient != null) { encrypter.addKeyTransRecipient(ciRecipient.getX509Certificate()); } else { // Now we could have a funny situation. The following might happen: a mail has // to send to 3 recipients. 1 has no certificate and the bypasssmime is enabled. // What to do now? We need to create a new version of the mail in plain text and // remove all recipients except this one. NOTE: We cannot avoid the recipient // getting 2 mails: 1 unreadable version and 1 plain one. This is beacuse we // cannot remove the recipient from the original message because that message // has been signed. if (eicConfiguration.getBypassSMIME()) { if (LOG.isDebugEnabled()) { LOG.debug( "BypassSMIME is enabled, so going to send a plain text version for user " + ia); } MimeMessage mmPlain = new MimeMessage(mmMessage); mmPlain.setRecipient(RecipientType.TO, ia); mmPlain.saveChanges(); lMessages.add(mmPlain); } else { // We need to throw an error since we cannot encrypt to all users. throw new OutboundEmailException( OutboundEmailExceptionMessages.OEE_COULD_NOT_FIND_A_CERTIFICATE_FOR_RECIPIENT_0, ia.toString()); } } } // Encrypt the message MimeBodyPart encryptedPart = encrypter.generate(mmMessage, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC"); // Create a new MimeMessage that contains the encrypted and signed content ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); MimeMessage encryptedMessage = new MimeMessage(sSession, new ByteArrayInputStream(out.toByteArray())); // Set all original MIME headers in the encrypted message Enumeration<?> headers = mmMessage.getAllHeaderLines(); while (headers.hasMoreElements()) { String headerLine = (String) headers.nextElement(); // Make sure not to override any content-* headers from the original message if (!Strings.toLowerCase(headerLine).startsWith("content-")) { encryptedMessage.addHeaderLine(headerLine); } } // Add the encrypted message to the list so that it will be sent. lMessages.add(encryptedMessage); } catch (Exception e) { throw new OutboundEmailException(e, OutboundEmailExceptionMessages.OEE_ERROR_ENCRYPTING_THE_MAIL); } }
From source file:com.cordys.coe.test.smime.TestSendEncryptedAndSignedMessage.java
License:Apache License
/** * This method sends the message to the receiver. * * @throws Exception DOCUMENTME// ww w . j av a 2 s .c om */ private void sendMessage() throws Exception { final InternetAddress[] RECEIVER_ADDRESS = new InternetAddress[] { new InternetAddress("outlook2007@ces70.cordys.com", "Outlook 2007 User"), new InternetAddress("outlookexpress@ces70.cordys.com", "Outlook Express User"), new InternetAddress("thunderbird@ces70.cordys.com", "Thunderbird User"), new InternetAddress("cordystestuser1@ces70.cordys.com", "Cordys Test User 1"), new InternetAddress("cordystestuser2@ces70.cordys.com", "Cordys Test User 2") }; final InternetAddress SENDER_ADDRESS = new InternetAddress("testprogram@ces70.cordys.com", "Test Program User"); String sSubject = "From test progam V1 [S&E] No r"; boolean bDoEncryption = true; // String sContent = "Single line"+System.getProperty("line.separator")+"SecondLine"; String sContent = "Single line\nSecondLine"; // Add capabilities. MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mailcap.addMailcap( "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); mailcap.addMailcap( "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); mailcap.addMailcap( "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); mailcap.addMailcap( "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); mailcap.addMailcap( "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(mailcap); /* Add BC */ Security.addProvider(new BouncyCastleProvider()); /* Get the private key to sign the message with */ ICertificateInfo certInfo = m_km.getCertificateInfo(SENDER_ADDRESS.getAddress()); if (certInfo == null) { throw new Exception("cannot find private key for email address " + SENDER_ADDRESS); } /* Create the message to sign and encrypt */ Properties props = System.getProperties(); props.put("mail.smtp.host", "srv-nl-ces70"); Session session = Session.getDefaultInstance(props, null); MimeMessage body = new MimeMessage(session); body.setContent(sContent, "text/plain"); body.saveChanges(); /* Create the SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); X509Certificate cert = certInfo.getX509Certificate(); ASN1EncodableVector attributes = new ASN1EncodableVector(); X509Name name = new X509Name(cert.getIssuerDN().getName()); IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name, cert.getSerialNumber()); SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute( issuerAndSerialNumber); attributes.add(encryptionKeyPreferenceAttribute); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSigner((PrivateKey) certInfo.getKey(), cert, "DSA".equals(certInfo.getKey().getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1 : SMIMESignedGenerator.DIGEST_MD5, new AttributeTable(attributes), null); /* Add the list of certs to the generator */ List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); signer.addCertificatesAndCRLs(certs); /* Sign the message */ MimeMultipart mm = signer.generate(body, "BC"); MimeMessage signedMessage = new MimeMessage(session); /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); /* Create the encrypter */ if (bDoEncryption) { SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); for (InternetAddress ia : RECEIVER_ADDRESS) { ICertificateInfo ciTemp = m_km.getCertificateInfo(ia.getAddress()); if (ciTemp != null) { encrypter.addKeyTransRecipient(ciTemp.getX509Certificate()); } else if (LOG.isDebugEnabled()) { LOG.debug("No certificate found for " + ia.toString()); } } /* Encrypt the message */ MimeBodyPart encryptedPart = encrypter.generate(signedMessage, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC"); /* * Create a new MimeMessage that contains the encrypted and signed content */ ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); body = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray())); } else { body = signedMessage; } body.setFrom(SENDER_ADDRESS); body.setRecipients(Message.RecipientType.TO, RECEIVER_ADDRESS); body.addRecipient(Message.RecipientType.TO, new InternetAddress("intermediate@ces70.cordys.com", "Intermediate user")); body.setSentDate(new Date()); body.addHeader("User-Agent", "CordysMailClient"); body.setSubject(sSubject); Transport.send(body); }
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
/** * @param cert//from w ww .j a v a 2 s . co m * @param algo * @param bp * @return * @throws NoSuchAlgorithmException * @throws CertificateEncodingException * @throws GeneralSecurityException */ public static MimeBodyPart smimeEncrypt(Certificate cert, EncryptionAlgo algo, BodyPart bp) throws NoSuchAlgorithmException, CertificateEncodingException, GeneralSecurityException { tstArgIsType("body-part", bp, MimeBodyPart.class); tstObjArg("cert", cert); tstObjArg("algo", algo); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); Provider prov = Crypto.getInstance().getProvider(); RecipientInfoGenerator g; try { g = new JceKeyTransRecipientInfoGenerator((X509Certificate) cert).setProvider(prov); gen.addRecipientInfoGenerator(g); return gen.generate((MimeBodyPart) bp, new JceCMSContentEncryptorBuilder(algo.getOID()).setProvider(prov).build()); } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } catch (CMSException e) { throw new GeneralSecurityException(e); } catch (SMIMEException e) { throw new GeneralSecurityException(e); } }
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
/** * @param cert//from w w w . j av a 2s. c o m * @param algo * @param msg * @return * @throws Exception */ public static MimeBodyPart smimeEncrypt(Certificate cert, EncryptionAlgo algo, MimeMessage msg) throws Exception { tstObjArg("mime-message", msg); tstObjArg("cert", cert); tstObjArg("algo", algo); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); Provider prov = Crypto.getInstance().getProvider(); RecipientInfoGenerator g = new JceKeyTransRecipientInfoGenerator((X509Certificate) cert).setProvider(prov); gen.addRecipientInfoGenerator(g); return gen.generate(msg, new JceCMSContentEncryptorBuilder(algo.getOID()).setProvider(prov).build()); }
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
/** * @param cert// w w w .j a v a 2 s . c om * @param algo * @param mp * @return * @throws MessagingException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws GeneralSecurityException * @throws CertificateEncodingException */ public static MimeBodyPart smimeEncrypt(Certificate cert, EncryptionAlgo algo, Multipart mp) throws MessagingException, NoSuchAlgorithmException, NoSuchProviderException, GeneralSecurityException, CertificateEncodingException { tstObjArg("multi-part", mp); tstObjArg("cert", cert); tstObjArg("algo", algo); try { SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); Provider prov = Crypto.getInstance().getProvider(); RecipientInfoGenerator g = new JceKeyTransRecipientInfoGenerator((X509Certificate) cert) .setProvider(prov); gen.addRecipientInfoGenerator(g); MimeMessage mm = newMimeMsg(); mm.setContent(mp); return gen.generate(mm, new JceCMSContentEncryptorBuilder(algo.getOID()).setProvider(prov).build()); } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } catch (SMIMEException e) { throw new GeneralSecurityException(e); } catch (CMSException e) { throw new GeneralSecurityException(e); } }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * @param algorith a algorith alias name, e.g. "3des", wil be translated * into the right IOD number internal//from www. ja va 2 s.c o m */ public MimeBodyPart encrypt(MimeMessage part, Certificate cert, String algorithm) throws Exception { X509Certificate x509Cert = castCertificate(cert); String encAlgOID = this.convertAlgorithmNameToOID(algorithm); SMIMEEnvelopedGenerator generator = new SMIMEEnvelopedGenerator(); generator.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(x509Cert).setProvider("BC")); if (part == null) { throw new GeneralSecurityException("encrypt: Part is absent"); } MimeBodyPart encData = generator.generate(part, new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier(encAlgOID)).setProvider("BC").build()); return encData; }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * @param algorith a algorith alias name, e.g. "3des", will be translated * into the right IOD number internal/*from w ww .j av a 2 s. co m*/ */ public MimeBodyPart encrypt(MimeBodyPart part, Certificate cert, String algorithm) throws Exception { X509Certificate x509Cert = castCertificate(cert); String encAlgOID = this.convertAlgorithmNameToOID(algorithm); SMIMEEnvelopedGenerator generator = new SMIMEEnvelopedGenerator(); generator.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(x509Cert).setProvider("BC")); if (part == null) { throw new GeneralSecurityException("encrypt: Part is absent"); } MimeBodyPart encData = generator.generate(part, new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier(encAlgOID)).setProvider("BC").build()); return encData; }