i am doing a class with static methods to encrypt and decrypt a message using javax.crypto. I have 2 static methods that use ecipher and dcipher in order to do what they are supossed to do i need to initialize some variables (which are static also). But when i try to use it i get InvalidKeyException with the parameters i give to ecipher.init(...). I can't find why. Here is the code:
private static byte[] raw = {-31, 17, 7, -34, 59, -61, -60, -16,
26, 87, -35, 114, 0, -53, 99, -116,
-82, -122, 68, 47, -3, -17, -21, -82,
-50, 126, 119, -106, -119, -5, 109, 98};
private static SecretKeySpec skeySpec;
private static Cipher ecipher;
private static Cipher dcipher;
static {
try {
skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, skeySpec);
dcipher.init(Cipher.DECRYPT_MODE, skeySpec);
} catch (NoSuchAlgorithmException e) {
throw new UnhandledException("No existe el algoritmo deseado", e);
} catch (NoSuchPaddingException e) {
throw new UnhandledException("No existe el padding deseado", e);
} catch (InvalidKeyException e) {
throw new UnhandledException("Clave invalida", e);
}
}
解决方案
AES-256 (and AES-192) requires the Unlimited Strength Jurisdiction Policy Files (one fo the last downloads at http://java.sun.com/javase/downloads/index.jsp) to be installed for the JRE. Not having this support will result in the InvalidKeyException when attempting to use 192 or 256 bit keys, as in your class.
The maximum allowed key size for AES without unlimited strength is documented in the JCA Reference Guide for Java 6, and by this happens to be 128-bits.