Search code examples
javasslbouncycastle

SMTP client using BouncyCastle's lightweight TLS API


I need to add TLS support to a simple Java-based SMTP client. The client implements the SMTP protocol over java.net.Socket, i.e. it does not use Java Mail or other high level APIs.

I would like to use BouncyCastle's lightweight TLS API for this task. I have been looking for examples but haven't been able to find too much. Can anyone give any pointers?


Solution

  • Turns out this was much easier than I expected. I could establish a secure SSL connection to a SMTP mail server by just modifying the original SMTP client code from this:

    Socket s = new Socket(server, port);
    InputStream is = s.getInputStream();
    InputStream os = s.getOutputStream();
    [...]
    

    To this:

    Socket s = new Socket(server, port);
    TlsProtocolHandler handler = new TlsProtocolHandler(s.getInputStream(),
                                                        s.getOutputStream());
    handler.connect(new AlwaysValidVerifyer());
    InputStream is = handler.getInputStream();
    InputStream os = handler.getOutputStream();
    [...]
    

    The server's certificate is not being verified yet (AlwaysValidVerifier is a dummy verifier that will accept anything) but this is a good start already.