Thursday, September 8, 2016

JavaMail, SSL and TLS

For my current project I've had to research the Java Mail api for reading pop3 mail boxes through secure connections, so I thought I'd write a bit about this to save someone else's frustrations.

Currently, SSLv3 is widely unsupported by commercial applications as it is insecure, and it is by default disabled in the JRE. If you need to enable it, comment the line "jdk.tls.disabledAlgorithms=SSLv3" in the java.security file under JRE/lib/security.

TLS 1.0 is the most supported as it is deemed the most secure. TLS 1.1 and 1.2 have more limited support.

This is how you read a pop3 mailbox using TLS:

Properties props = new Properties();

props.put("mail.pop3s.host", "myhost");
props.put("mail.pop3s.port", "995");

props.put("mail.pop3s.ssl.protocols", "TLSv1 TLSv1.1 TLSv1.2");

props.put("mail.pop3s.ssl.enable", "true");
// Add your host here if you want more security; this is enough for testing.
props.put("mail.pop3s.ssl.trust", "*"); 

Session emailSession = Session.getInstance(props);

Store store = emailSession.getStore("pop3s");
store.connect("username", "password");

store.close();


I've tested this successfully with hMailServer using TLS 1.0, 1.1 and 1.2.

If you get that dreaded "PKIX path building failed" exception while connecting, you need to create a self-signed certificate for your server, import it there and add it to your JRE keystore. Trusted authority certificates should work by default (like Google). There's plenty of resources online how to do this so I won't cover it here, just Google how to create self-signed cert using OpenSSL and how to import certificates with java keytool.