Vladimir Dyuzhev
Vladimir Dyuzhev

Reputation: 18336

How to get the actual block cipher key size for Java SSL connection _in code_?

When a Java client has established a SSL/TLS session, it can get the used protocol and the cipher name:

    SSLSession session = s.getSession();
    String protocol = session.getProtocol(); // e.g. "TLSv1"
    String cipher = session.getCipherSuite(); // e.g. "TLS_RSA_WITH_AES_128_CBC_SHA"

But some of the ciphers can have keys of size 128 or 256 (for example, AES CBC).

How can I get the actual key size negotiated for this particular connection?

I have found this code in Apache codebase:

static final CipherData cipherSizes[] = {
    new CipherData("_WITH_NULL_", 0),
    new CipherData("_WITH_IDEA_CBC_", 128),
    new CipherData("_WITH_RC2_CBC_40_", 40),
    new CipherData("_WITH_RC4_40_", 40),
    new CipherData("_WITH_RC4_128_", 128),
    new CipherData("_WITH_DES40_CBC_", 40),
    new CipherData("_WITH_DES_CBC_", 56),
    new CipherData("_WITH_3DES_EDE_CBC_", 168),
    new CipherData("_WITH_AES_128_CBC_", 128),
    new CipherData("_WITH_AES_256_CBC_", 256)
};  

It looks like an acceptable workaround. Is it the only way to do it?

Upvotes: 3

Views: 573

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94048

You can simply parse the key size out of the connection string. If it's DES EDE it's 168 (or 192 if you count the parity bits). Otherwise it has a default or the key size is directly behind the name of the symmetric algorithm.

I would say that the Apache way seems a very acceptable way to do it yes. You'll have to manually insert the default key sizes - for those ciphers such as IDEA - anyway. Instantiating a Cipher object just to get to the acceptable key sizes seems overkill to me.

Abstraction/automation is all very nice but you can go too far. Nothing wrong with a (semi) hard coded table here.

Upvotes: 3

Related Questions