1

Given a javax.crypto.Cipher object, how do I obtain key length to use with its init method?

I do know that object is created with Cipher.getInstance("AES/CBC/PKCS5Padding"), but I'd like to abstract from that.

Right now my code looks like:

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(keyString.toCharArray(), SALT, 256, 128);
        byte[] encoded = factory.generateSecret(spec).getEncoded(); 
        assert encoded.length*8 == 128;
        Key rv = new SecretKeySpec(encoded, "AES");
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        cipher.init(Cipher.DECRYPT_MODE, rv, new IvParameterSpec(IV_PARAMETER_SPEC));

I'd like replace cipher object with a parameter and "128", "AES" constant values to be derived from cipher object.

Basilevs
  • 22,440
  • 15
  • 57
  • 102

2 Answers2

2

There is no direct way to do that, and it is a probably not a good idea to do it either. Some ciphers may have very short or very long keys, neither of which are very useful. RSA does not even have a maximum key size, and the minimum key size is often insecure.

There is the method getMaxAllowedKeyLength but that may simply return Integer.MAX_VALUE instead of the maximum key size in bits. It should only be used to check a known key length against restrictions.

You are better off storing the key size as a property/resource somewhere if you want to make it configurable. In my opinion it is not a good idea to abstract this decision away.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
0

Read the documentation for the algorithm you want to use and write a class which encapsulates the specifics for that algorithm in terms of maximum key length.

Tommy B
  • 187
  • 2
  • 8
  • This will only work for known algorithms. The question is about extracting information about algorithm to parameter making it potentailly unknown. – Basilevs May 27 '14 at 03:56
  • I see your point. The only crux is that it can't be done, so if you want encapsulation of the values for algo and key length you have to provide it yourself. – Tommy B May 27 '14 at 05:38