Question

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
Was it helpful?

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;
}

OTHER TIPS

You are using an older Java version that does not handle 128 bit key lengths. In principle, 3DES always uses three keys - keys ABC - which are 64 bit each when we include the parity bits into the count (for a single DES encrypt with A, then decrypt with B, then encrypt again with C). 128 bit (dual) key however uses A = C. So to create a valid 24 byte key, you need to copy and concatenate the first 8 bytes to the tail of the array. Or you could upgrade to a newer JRE, or use a provider that does accept 16 byte 3DES keys.

Note that 192 bit (168 bit effective) 3DES keys are quite a bit more secure than 128 (112 bit effective) bit keys; 128 bit 3DES is not accepted by NIST (which handles US government standardization of cryptography) anymore. You should try and switch to AES if possible; AES doesn't have these kind of shenanigans and is much more secure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top