3DES Decryption Error Invalid Key Length

前端 未结 2 1990
無奈伤痛
無奈伤痛 2020-12-18 17:20

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

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

My Co

相关标签:
2条回答
  • 2020-12-18 17:39

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 17:47

    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.

    0 讨论(0)
提交回复
热议问题