views:

172

answers:

2

Hello folks, 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);
        }
    }
+1  A: 

From SecretKeySpec doc:

This constructor does not check if the given bytes indeed specify a secret key of the specified algorithm. For example, if the algorithm is DES, this constructor does not check if key is 8 bytes long, and also does not check for weak or semi-weak keys. In order for those checks to be performed, an algorithm-specific key specification class (in this case: DESKeySpec) should be used.

I guess your bytes do not correspond to a valid key for AES. Here you can find an example on how to generate it. Suerte.

UPDATE: See also here.

UPDATE 2: As the other answer points out, you particular raw surely is invalid because your system does not support AES 256. Shorten it to 16 bytes (128 bits) and try again.

leonbloy
+3  A: 

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.

Vineet Reynolds
This was the problem.
noinflection