Java tutorials home Java cryptography Encryption intro Keys Symmetric encryption AES/block ciphers Block modes (ECB, CTR, OFB) Asymmetric encryption RSA in Java Comparison of algorithms Key sizes Hash functions
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.
How to set the key size in Java
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.
Which key size?
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:
Practical problems with using 256-bit keys in Java
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.
Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved.