InterestedDev
InterestedDev

Reputation: 588

DESedeKeySpec Wrong key size

I need to use double length 3DES key to encrypt random 8 bytes and then use the encrypted value to derive a new 3DES key.

When I attempt to instantiate the DESedeKeySpec with the encryptedRandomValue, I get an error message "Wrong key size". Can you advise me how to fix this issue?

DESedeKeySpec myKeySpec = new DESedeKeySpec(encryptedRandomValue);

I can avoid getting this error if all my SecretKeys are single DES key. But I need to use double length 3DES key and ECB mode.

Here is my code;

    // Generate double length 3DES Master Key
    KeyGenerator masterEncKeyGenerator = KeyGenerator.getInstance("DESede");
    masterEncKeyGenerator.init(112);
    SecretKey masterKey = masterEncKeyGenerator.generateKey();

    //Prepare random bytes
    byte[] randomKeyValue = "rn4yrbdy".getBytes();

    // Encrypt random bytes with the 3DES Master key
    final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, masterKey);
    byte[] encryptedRandomValue = cipher.doFinal(randomKeyValue);

    // Derive new key 3DES Key
    SecretKeyFactory mySecretKeyFactory = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec myKeySpec = new DESedeKeySpec(encryptedRandomValue);
    SecretKey derivedKey = mySecretKeyFactory.generateSecret(myKeySpec);

I realize why I am getting this error. It is because the DESedeKeySpec needs to take in 24 bytes as key material but I am giving it only 8. But that's the requirement I have: to produce a 3DES key out of encrypted, with master 3DES key, random 8 bytes data...

Upvotes: 1

Views: 3780

Answers (1)

Ebbe M. Pedersen
Ebbe M. Pedersen

Reputation: 7518

Triple DES is just 3 consecutive single DES operation done with different keys. Specifically it's a DES encrypt followed by a DES decrypt followed by a DES encrypt.

DES encrypt-decrypt-encrypt is what gives it the name DESede

The difference betwheen double length and tripple length keys is what part of the key you use in each of the three DES operation.

A double length key: k1 || k2 would give the following DES operations:

Encrypt(k1) - Decrypt(k2) - Encrypt(k1)

A tripple length key: k1 || k2 || k3 would give the following DES operations:

Encrypt(k1) - Decrypt(k2) - Encrypt(k3)

The standard implementation in Java don't support double length triple DES keys directly but you can get the same effect by repeating the first part of the key as the third part: k1 || k2 || k1

As a curiosity you can support single DES encryption via tripple DES by repeating the single DES key three times like: k1 || k1 || k1. This simplifies backword compatibility in e.g. hardware implementations.

Upvotes: 5

Related Questions