Deepak P C
Deepak P C

Reputation: 33

Java - SHA-256 hashing : Invalid AES key length : 64 bytes

public static String doGenerate() {
    int val = 10000000;
    Random r = new Random();
    int gen = r.nextInt(89999999);
    int gen1 = r.nextInt(89999999);
    gen = val + gen;
    gen1 = val + gen1;
    String reply = gen + "" + gen1;
    return reply;
}

This is the method I use to generate a key I need for the AES algorithm given below.

public static void decryptFile(String keyString, String fileName){
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        SecretKey key = (SecretKey) new SecretKeySpec(
            keyString.getBytes(), "AES");// kgen.generateKey();

        AESEncrypter encrypter = new AESEncrypter(key);

        encrypter.decrypt(new FileInputStream(
            new java.io.File("").getCanonicalFile() +
            File.separator + "Received"+
            File.separator + fileName),
            new FileOutputStream(new java.io.File("").getCanonicalFile() +
            File.separator + "Decrypted" + 
            File.separator + fileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is the AESEncrypter method.

  public AESEncrypter(SecretKey key) {
    // Create an 8-byte initialization vector
    byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
            0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

    AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
    try {
        ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // CBC requires an initialization vector
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

After decrypting I get an invalid key exception: java.security.InvalidKeyException: Invalid AES key length: 64 bytes. Why is this happening? Is there a solution for this?

Upvotes: 1

Views: 3645

Answers (1)

Duncan Jones
Duncan Jones

Reputation: 69389

Your key generation function is flawed - it produces only integers and converts those to strings, massively reducing the available key space and weakening your keys significantly.

However, it does produce 16 byte values which are suitable for AES keys. I can only assume you've changed your code since you last received the error message?

I strongly recommend you revert to just using the KeyGenerator to produce your AES keys. That will do so in a secure fashion.

Upvotes: 1

Related Questions