Thursday, July 8, 2010

Java Socket Encryption

When you're writing a web application that transmits sensitive content, it's obviously a good idea to encrypt your socket connections. How is this done?

Step 1) Open an SSLSocket or SSLServerSocket:
SSLSocketFactory sslFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket)sslFactory.createSocket(ipString, portInt);

or

SSLServerSocketFactory sslSrvFactory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket serverSocket = (SSLServerSocket)sslSrvFactory .createServerSocket(port);

Step 2) Negotiate an encryption suite:
// Pick all AES algorithms of 128 bits key size
String patternString = "AES.*128";
          Pattern pattern = Pattern.compile(patternString);
          Matcher matcher;
          boolean matchFound;
          
       String supportedSuites[] = server.getSupportedCipherSuites();

       // What we're really doing here is ordering the suites by
       // how much we prefer the suite for this connection. the ssl layers
       // beneath will choose the best pick suite that is common.
       String suitePickOrder[] = new String[supportedSuites.length];

       int j=0, k = supportedSuites.length-1;
       for (int i=0; i < supportedSuites.length; i++)
       {
        // Determine if pattern exists in input
        matcher = pattern.matcher(supportedSuites[i]);
        matchFound = matcher.find();
        
        if (matchFound)
         suitePickOrder[j++] = supportedSuites[i];
        else
         suitePickOrder[k--] = supportedSuites[i];
       }

       server.setEnabledCipherSuites(suitePickOrder);


SSL requires both client and server (or peer and peer) to use the same encryption algorithm. Part of establishing an SSL connection is the negotiation of which encryption "suite" to use. Each user prepares a list of available suites in, ordered the way they deem desirable.

In the code above we chose to make AES 128-bit schemes the most desirable. AES is the federal encryption standard. The NSA has cleared 256-bit AES for encrypting classified documents up to TOP SECRET (have fun working around the export control restrictions so that you can actually use the 256-bit variant though.)

The SSL layers will now handle all of the remaining setup and encryption, and you can treat your new SSLSockets as if they were normal Sockets. Your streaming data is now safe.

No comments :

Post a Comment