Basilevs
Basilevs

Reputation: 23939

How to get Cipher's maximum key size

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.

Upvotes: 1

Views: 2180

Answers (2)

Tommy B
Tommy B

Reputation: 185

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.

Upvotes: 0

Maarten Bodewes
Maarten Bodewes

Reputation: 94038

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.

Upvotes: 2

Related Questions