views:

36

answers:

2

I have to write a program to decrypt a message using JAVA. The message is encrypted using Triple DES / ECB implemented in PHP. I have tried a few different settings on the algorithm, mode, and padding schema. I do not get the correct result. What is missing?

Here is the PHP program that encrypt the message:

$config_mcrypt_ecb_key = "12345678901234567890";
$data = "hello";
echo "Data Before Encrypt: " . $data . "\n";
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_ENCRYPT);
mcrypt_generic_init($td, $config_mcrypt_ecb_key, $iv);
$data_encrypt = bin2hex(mcrypt_generic($td, $data));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
echo "Data After Encrypt: " . $data_encrypt . "\n";

And below is the java program to decrypt the message: (I'm using the BouncyCastleProvider)

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

public class DecryptionTest {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException {
        String password = "12345678901234567890";
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        SecretKeySpec key = new SecretKeySpec(password.getBytes(), "ECB");
        Cipher m_decrypter = Cipher.getInstance("DESede/ECB/ZeroBytePadding");
        m_decrypter.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedText = m_decrypter.doFinal("bdf0baf948bff7e7".getBytes());
        System.out.println(new String(decryptedText));
    }
}
A: 

You don't seem to be using an IV (Initialisation Vector) when performing the decrypt. My understanding is that mcrypt_create_iv() will generate a random IV, so you need to store that with the encrypted data so that it can be used when decrypting.

Alternatively (if you're happy with using a weaker encryption) omit the IV from your PHP side.

PaulG
I have tried adding the IV too. It is failed with an exception "java.security.InvalidAlgorithmParameterException: ECB mode does not use an IV". I have google about IV. It said that ECB will ignore the IV.
zzpaul