As well as choosing an encryption algorithm, you must generally choose a key size to use with that algorithm. In a loose way, the key size determines the "strength" of encryption, assuming that the actual algorithm is otherwise secure. Specifically, the key size generally determines: the number of guesses that an attacker would need to make in order to find the key by "brute force", assuming that all possible keys are equally likely. Relatedly, it also determines the chance and feasibility of a collision attack.
Note that on this page, we are concerned with the key size of symmetric encryption algorithms— that is, where a shared secret key is used by all parties. In geneal, asymmetric algorithms require a larger key size measured bit-for-bit. We discuss RSA key sizes on a separate page.
If you use the KeyGenerator class, then you can set the key size in bits via the init() method. The following example shows how to generate a 256-bit AES key:
KeyGenerator gen = KeyGenerator.getInstance("AES/CTR/PKCS5PADDING"); gen.init(256); SecretKey k = gen.generateKey(); Cipher ciph = Cipher.getInstance("AES"); ciph.init(Cipher.ENCRYPT_MODE, k); ...
Note that attempting to use this key with Sun's JDK "out-of-the-box" will throw an InvalidKeyException due to an (overridable) policy restriction that limits symmetric keys to 128 bits. Below, we describe how to remove this 128-bit description, and how to determine if a given client has this restriction.
In general, the minimum required key size is some combination of the maximum key size that can be attacked now for a given algorithm, extrapolated to the number of years that you need to keep the encrypted data confidential. Needless to say, such extrapolation is extremely difficult beyond a few years. A couple of pointers are:
The conclusions I draw from this are:
There are a couple of practical problems with using 256-bit keys in Java:
If your deployment model allows it, the 128-bit restriction can be removed by downloading and manually installing Unlimited Strength Jurisdiction Policy Files provided by Sun.
1. Lenstra, A. K. & Verheul, E. R. (2001)
Selecting Cryptographic Key Sizes,
Journal of Cryptology 14(4):255-293.
2. Ferguson, N. & Schneier, B. (2003), Practical Cryptography, Wiley.
3. NIST (2006), Recommendation for Key Management: Part 1, NIST.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants. Follow @BitterCoffey
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.