By MkHeck on Jan 14, 2013
I've been working recently with a client to do some rather useful things with notifications, and one of them involved sending a secure email from within a Java program. We encountered some interesting (translation: weird!) challenges, and in overcoming them, I worked out a reasonably straightforward path through the minefield. If you've been thinking about secure-email-enabling your Java app but aren't sure where to start, hopefully this will serve as a fairly quick and mostly painless primer. :-)
The goal is to digitally sign an email to assure recipients that the sender of the mail is indeed me (or you, if you're following along at work/home). Let's get started!
Getting Your Tools in Order
Getting a Certificate
Freeing the Certificate from your Browser
- Click on the Wrench (or Lines) icon in the upper-right corner
- Select "Settings" from the menu
- "Show advanced settings..." at the bottom of the page
- Scroll down to the section labeled "HTTPS/SSL"
- Click the "Manage certificates..." button to display your certificates.
- Select the target certificate and click the "Export..." button
- Click "Next" from the Export Wizard window
- Choose "Yes, export the private key" and click "Next"
- Under the "Personal Information Exchange - PKCS #12 (.PFX)" entry, select the options to "Include all certificates in the certification path if possible" and "Export all extended properties" (NOTE: Do NOT choose to "Delete the private key if the export is successful". No no no!) and click "Next"
- Enter a password (twice) and click "Next"
- Provide a path/filename for the export and click "Next", and finally...
- Confirm the export options and click "Finish".
Creating a Java Keystore
- Create an ORACLE_HOME environment variable that points to the install location of the Oracle client
- Run the following command, pointing to the orapki utility under %ORACLE_HOME%\bin (in Windows) or $ORACLE_HOME/bin (Mac/Linux/UNIX):
orapki wallet pkcs12_to_jks -wallet <wallet_directory> -pwd <wallet_password> -jksKeyStoreLoc <java_key_store_path_and_filename> -jksKeyStorepwd <jks_password>
Now that we have our credentials in order, on to the Java side of things!
Building the Solution
- Provide the email "essentials": SMTP server host & port, email addresses (sender & receiver), a subject, content, and the sending user's password
- Add BC as a new crypto provider
- Retrieve the cert from your Java Keystore
- Create and sign the email using the BC API/libraries
- Send the email
- The BC provider library (bcprov-jdk15on-147.jar)
- The BC S/MIME library (bcmail-jdk15on-147.jar)
- The BC security library (bcpkix-jdk15on-147.jar)