开发者

Encrypt with PHP and Decrypt with Java

开发者 https://www.devze.com 2023-01-21 21:02 出处:网络
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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消