I need to create a double length 3DES key in Java using a 16 bytes array key material, encrypt with it a message and get back 16 bytes length array. I am able to get it working with 24 bytes but not 16 bytes…
Because DESede expects 24 byte, the only way to produce a double length 3DES Key with a 16 bytes long key material, I was able to by using a DESede instance and then increasing its length by appending first 8 bytes at the end to get 24 bytes. Like so:
byte keyMaterial = // Assume this one is 16 bytes. byte newKeyBytes = ByteBuffer.wrap( new byte[ 24 ] ) .put( Arrays.copyOfRange( keyMaterial, 0, 16 ) ) .put( Arrays.copyOfRange( keyMaterial, 0, 8 ) ) .array(); SecretKeyFactory mySecretKeyFactory = SecretKeyFactory.getInstance( "DESede" ); KeySpec myKeySpec = new DESedeKeySpec( newKeyBytes ); SecretKey encryptionKey = mySecretKeyFactory.generateSecret( myKeySpec );
Now when I have my DESede key I can use it to encrypt the message the following way. Also, I need to use “ECB” mode:
Cipher cipher = Cipher.getInstance( "DESede/ECB/PKCS5Padding" ); cipher.init( Cipher.ENCRYPT_MODE, encryptionKey ); byte returnValue = cipher.doFinal( dataToEncrypt )
But as a result I get back 24 byte array rather than 16 byte array and I guess this is because I am encrypting with 24 byte array.
Is there a way to create a 3DES SecretKey 16 bytes long rather than 24 bytes, OR when encrypting with 24 byte long SecretKey, get back a 16 bytes long ciphered message as I need rather than 24 bytes long?
I think I have just found an answer to my question.
I used DESede/ECB/NoPadding and when used with NoPadding, then encrypting a 16 bytes array message with 24 bytes SecretKey produces a 16 bytes long cipher message which is exactly what I need.
I hope this finding is correct. Please correct me if I am mistaken.