Skip to content

Instantly share code, notes, and snippets.

@stephen-marc
Created April 27, 2015 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephen-marc/a8d8146476bccfe4f979 to your computer and use it in GitHub Desktop.
Save stephen-marc/a8d8146476bccfe4f979 to your computer and use it in GitHub Desktop.
public static void main(
String args[])
throws Exception
{
if (args.length != 2)
{
System.err.println("usage: CreateEncryptedMail pkcs12Keystore password");
System.exit(0);
}
//
// Open the key store
//
KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
ks.load(new FileInputStream(args[0]), args[1].toCharArray());
Enumeration e = ks.aliases();
String keyAlias = null;
while (e.hasMoreElements())
{
String alias = (String)e.nextElement();
if (ks.isKeyEntry(alias))
{
keyAlias = alias;
}
}
if (keyAlias == null)
{
System.err.println("can't find a private key!");
System.exit(0);
}
Certificate[] chain = ks.getCertificateChain(keyAlias);
//
// create the generator for creating an smime/encrypted message
//
SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();
gen.addKeyTransRecipient((X509Certificate)chain[0]);
//
// create a subject key id - this has to be done the same way as
// it is done in the certificate associated with the private key
// version 3 only.
//
/*
MessageDigest dig = MessageDigest.getInstance("SHA1", "BC");
dig.update(cert.getPublicKey().getEncoded());
gen.addKeyTransRecipient(cert.getPublicKey(), dig.digest());
*/
//
// create the base for our message
//
MimeBodyPart msg = new MimeBodyPart();
msg.setText("Hello world!");
MimeBodyPart mp = gen.generate(msg, SMIMEEnvelopedGenerator.RC2_CBC, "BC");
//
// Get a Session object and create the mail message
//
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
Address fromUser = new InternetAddress("\"Eric H. Echidna\"<eric@bouncycastle.org>");
Address toUser = new InternetAddress("example@bouncycastle.org");
MimeMessage body = new MimeMessage(session);
body.setFrom(fromUser);
body.setRecipient(Message.RecipientType.TO, toUser);
body.setSubject("example encrypted message");
body.setContent(mp.getContent(), mp.getContentType());
body.saveChanges();
body.writeTo(new FileOutputStream("encrypted.message"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment