From Socket to SSLSocket

The deal today is to secure a simple TCP server / client in java by using SSLSockets.

About SSL

Before starting, a few concepts need to be understood. For an in-depth review: Java Secure Socket Extension (JSSE) Reference Guide.

Why use SSL?

Using SSL addresses three potential issues when transferring sensitive data over a network:

  • Authentication: SSL provides a way to confirm that the sender is who it claims it is.
  • Security: with the right encryption algorithm, SSL protected data is virtually impossible to decrypt by an unauthorised party.
  • Integrity: the data can’t be modified by an attacker (if it is, it is detected).

Integrity is guaranteed by the use of a cryptographic hash function, which acts like a checksum: if the message is modified, even slightly, the resulting hash will be significantly different. Examples: MD5 (Message Digest 5) and SHA (Secure Hash Algorithm).

Hash Message Authentication Code (HMAC) is the process of including the hash in the message before encryption with a secret key (symmetric cryptography).

Cryptographic Process

  • Asymmetric cryptography: Party A encrypts data with a private key. That data can be decrypted by B if B has A’s public key. That provides authentication: B can confirm that it’s really A who sent the data, but anyone who has the public key can decrypt the data. The decryption process is slow. Examples: RSA (Rivest Shamir Adleman) and DH (Diffie-Hellman) algorithms.
  • Symmetric cryptography: both parties use the same private key to encrypt and decrypt the messages. Encryption/decryption is fast but the private key needs to be exchanged securely. Examples: DES (Data Encryption Standard), 3DES (triple-strength DES), RC2 and RC4 (Rivest Cipher 2 and 4).

A public key certificate can be obtained from a certificate authority (CA) and is a proof that the sender of a public key is who he claims he is. The way it works is (in a simpified way):

  • The SSL certificate, which includes details about the CA is signed with the private key of the certified party (A).
  • When a third party connects to A, it receives the encrypted certificate, which only A can have encrypted, using his private key and which can only be decrypted by A’s public key.

How does SSL work?

A SSL connection starts with a handshake which mainly consists of the following two steps:

  • Cipher Suite: the 2 parties agree on a cryptographic algorithm. The client lets the server know which algorithms it can handle and the server decides which is best.
  • Authentication of the server: optional step where the server sends its public key certificate. The client then generates a private key which will be used for symmetric cryptography later on. It encrypts that secret key with the server’s public key. Only the server can decrypt the secret key.

Both parties now have the same secret key and can start exchanging secured data.

So shall we start now?

Create private and public keys for the server

There are several types of keystore – by default Java uses a JKS keystore. We generate a RSA key pair of 3048 bits with keytool. 3048 is chosen based on this which states:

Conservatively applying Lenstra and Verheul’s “law”, i.e., incorporating 18 “generations” of such improvements, a $10 million “future TWIRL” in the year 2030 would take about five months to factor a 2048-bit RSA key.

>keytool -genkeypair -keyalg RSA -keysize 3072 -dname "cn=assylias, o=assylias.Inc, c=FR" -alias test -keypass keypass -storepass storepass -validity 36500 -keystore C:\temp\keystore.test

We can check that everything went fine:

>keytool -list -v -keystore C:\temp\keystore.test

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: test
Creation date: 01-Aug-2012
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=assylias, O=assylias.Inc, C=FR
Issuer: CN=assylias, O=assylias.Inc, C=FR
Serial number: 6d75c1c3
Valid from: Wed Aug 01 15:18:17 BST 2012 until: Fri Jul 08 15:18:17 BST 2112
Certificate fingerprints:
         MD5:  66:8E:EA:75:35:BE:E2:72:70:A6:B2:4E:48:00:78:AB
         SHA1: 60:AA:CC:BB:D1:6D:B3:43:57:05:75:6E:6B:9C:A9:D5:BF:A5:66:7A
         SHA256: 33:E6:BC:3E:A6:2D:66:E7:3D:D4:89:20:EE:D3:BA:D3:1A:49:6B:04:44:8C:7E:9C:82:14:7B:50:72:66:1B:64
         Signature algorithm name: SHA256withRSA
         Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 48 F3 52 2E 0C 38 40 C0   B2 4E E9 8C 2E D5 91 E6  H.R..8@..N......
0010: C7 9E 10 46                                        ...F
]
]

We can then export a self signed certificate and check the content:

>keytool -export -alias test -keystore C:\temp\keystore.test -rfc -file C:\temp\test.cer
>type C:\temp\test.cer

-----BEGIN CERTIFICATE-----
MIIEDzCCAnegAwIBAgIEbXXBwzANBgkqhkiG9w0BAQsFADA3MQswCQYDVQQGEwJGUjEVMBMGA1UE
ChMMYXNzeWxpYXMuSW5jMREwDwYDVQQDEwhhc3N5b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t+PMoi5/ZY1mTWsr/O/XFLLcLw1pXmhs
20C4jIPk+x+CFFaITZvsk64cV2F1Kj0n20tkABF8TmYwTk+lCKELgk8WuG8nzO7+BMQgC7GG+7D0
K2hY3Ml7TprRM47Az7yHz3HjYtEeHrfHLKgq9QNx6SKYpn4UJPfx9cprUdBQotUfKhZMylMoaIr4
m177UQw6lRc10G+ddY2rjXk=
-----END CERTIFICATE-----

Let’s add that certificate to the truststore:

>keytool -import -alias test -file C:\temp\test.cer -keystore C:\temp\truststore.test

Owner: CN=assylias, O=assylias.Inc, C=FR
Issuer: CN=assylias, O=assylias.Inc, C=FR
Serial number: 6d75c1c3
Valid from: Wed Aug 01 15:18:17 BST 2012 until: Fri Jul 08 15:18:17 BST 2112
Certificate fingerprints:
         MD5:  66:8E:EA:75:35:BE:E2:72:70:A6:B2:4E:48:00:78:AB
         SHA1: 60:AA:CC:BB:D1:6D:B3:43:57:05:75:6E:6B:9C:A9:D5:BF:A5:66:7A
         SHA256: 33:E6:BC:3E:A6:2D:66:E7:3D:D4:89:20:EE:D3:BA:D3:1A:49:6B:04:44:8C:7E:9C:82:14:7B:50:72:66:1B:64
         Signature algorithm name: SHA256withRSA
         Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 48 F3 52 2E 0C 38 40 C0   B2 4E E9 8C 2E D5 91 E6  H.R..8@..N......
0010: C7 9E 10 46                                        ...F
]
]

Trust this certificate? [no]:  yes
Certificate was added to keystore

And let’s check that it’s been added:

>keytool -list -v -keystore C:\temp\truststore.test

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: test
Creation date: 01-Aug-2012
Entry type: trustedCertEntry

Owner: CN=assylias, O=assylias.Inc, C=FR
Issuer: CN=assylias, O=assylias.Inc, C=FR
Serial number: 6d75c1c3
Valid from: Wed Aug 01 15:18:17 BST 2012 until: Fri Jul 08 15:18:17 BST 2112
Certificate fingerprints:
         MD5:  66:8E:EA:75:35:BE:E2:72:70:A6:B2:4E:48:00:78:AB
         SHA1: 60:AA:CC:BB:D1:6D:B3:43:57:05:75:6E:6B:9C:A9:D5:BF:A5:66:7A
         SHA256: 33:E6:BC:3E:A6:2D:66:E7:3D:D4:89:20:EE:D3:BA:D3:1A:49:6B:04:44:8C:7E:9C:82:14:7B:50:72:66:1B:64
         Signature algorithm name: SHA256withRSA
         Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 48 F3 52 2E 0C 38 40 C0   B2 4E E9 8C 2E D5 91 E6  H.R..8@..N......
0010: C7 9E 10 46                                        ...F
]
]

Let’s amend the code

The original simple socket code is modified in the following way.

On the server side

    server = new ServerSocket(port);

becomes

    try {
        SSLContext context = SSLContext.getInstance("TLS");
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        KeyStore keyStore = KeyStore.getInstance("JKS");

        keyStore.load(new FileInputStream("C:/temp/keystore.test"), "storepass".toCharArray());
        keyManagerFactory.init(keyStore, "keypass".toCharArray());
        context.init(keyManagerFactory.getKeyManagers(), null, null);

        SSLServerSocketFactory factory = context.getServerSocketFactory();

        return factory.createServerSocket(port);
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }

On the client side

    server = new Socket(ip, port);

becomes

    System.setProperty("javax.net.ssl.trustStore", "C:/temp/truststore.test");
    System.setProperty("javax.net.ssl.trustStorePassword", "storepass");
    ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
    server = factory.createServerSocket(port);

Et voila. Next step: select the best cipher suites…

Advertisements
Tagged ,

One thought on “From Socket to SSLSocket

  1. sammy says:

    Hello,

    thank you for this useful articel,
    One thing i can’t unterstand, on the client side if i use “keystore.test” instead of “truststore.test” it works.

    I think the right way is to use “truststore”!! I am now totally confused 🙂

    Thanks in advance

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: