Skip to content
Advertisement

How to decrypt a string in PHP that was encrypted in Java?

I tried to decrypt en encrypted string in JAVA with to code below.

JavaScript
JavaScript

How can I get the same result with PHP version? I tried to write in PHP and It outputs with wrong result.

JavaScript

Advertisement

Answer

The build3DesKey() function expands a too short 3DES key to 24 bytes by padding the end with 0x00 values, for too long keys the end is simply truncated. build3DesKey() can be implemented in PHP as follows:

JavaScript

Although the str2ByteArray() function is missing, its functionality can be deduced. Since in your example the ciphertext is hexadecimal encoded, this function seems to simply perform a hex decoding. In PHP, the analog to str2ByteArray() is hex2bin().

Thus, a possible implementation for decryption is (using PHP/OpenSSL):

JavaScript

The Java code returns the same plain text for these input data!


Differences to your code:
Your code uses the deprecated mcrypt. This should not be applied nowadays for security reasons. A better alternative is PHP/OpenSSL, which is used in the code above. Also, the implemented key derivation is wrong, e.g. it applies the digest MD5, which is not used in the Java code at all.


Security:
Even though this is probably a legacy application, a few words about security:

  • The key derivation build3DesKey() is insecure. If the key material is a string, it is generally not a key, but a password. Therefore a reliable key derivation function should be used, e.g. Argon2 or PBKDF2.
  • des-ede3 applies ECB mode, which is also insecure. Nowadays authenticated encryption, e.g. AES-GCM should be used.
  • 3DES/TripleDES is outdated and the only not yet deprecated variant, triple-length keys or 3TDEA will be soon, and is comparatively slow. Today’s standard AES should be applied here.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement