Search code examples
javaencryptioncryptography3des

3DES Decryption Error Invalid Key Length


I am using 3DESC to decrypt data but i am getting following exception

java.security.InvalidKeyException: Invalid key length: 16 bytes

My Code:

public static byte[] decrypt3DESCBC(byte[] keyBytes, byte[] ivBytes,
        byte[] dataBytes) {
    try {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "DESede");
        Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec); // Causes Exception
        return cipher.doFinal(dataBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Printed all the byte array above used

keyBytes : FC15780BB4B0**********0876482C1B // Masked 10 Characters
ivBytes : 0000000000000000
dataBytes : AF53C90F7FAD977E**********69DB5A2BF3080F9F07F4BFEA3EDB4DE96887BE7D40A5A590C0911A // Masked 10 Characters

Solution

  • DES-EDE cipher can be used with 3 different subkeys therefore the key size should be 24 bytes (3 times 8 bytes). If you want to use only 2 keys (i.e. in this mode first key == last key) then you just have to duplicate the first 8 bytes of the key array.

    byte[] key;
    if (keyBytes.length == 16) {
        key = new byte[24];
        System.arraycopy(keyBytes, 0, key, 0, 16);
        System.arraycopy(keyBytes, 0, key, 16, 8);
    } else {
        key = keyBytes;
    }