P粉0142181242023-08-31 10:27:11
Function build3DesKey()
Extends a too short 3DES key to 24 bytes by padding the end with a 0x00 value, for too long keys the end is simply truncated. In PHP, it can be implemented as follows build3DesKey()
:
$key = substr(str_pad($key, 24, "$key = "12345"; $ciphertext = "84b24172c57752385251d142abadbed1d9945301a3aee429ce00c1e291a605c30ad18c5e00007f6db394fc6138a2ee4c"; $key = substr(str_pad($key, 24, "rrreee"), 0, 24); $plaintext = openssl_decrypt(hex2bin($ciphertext), "des-ede3", $key, OPENSSL_RAW_DATA); print($plaintext. PHP_EOL); // The quick brown fox jumps over the lazy dog"), 0, 24);
Although the function str2ByteArray()
is missing, its functionality can be inferred. Since in your example the ciphertext is hex encoded, this function seems to just perform hex decoding. In PHP, the counterpart to str2ByteArray()
is hex2bin()
.
So a possible implementation of decryption is (using PHP/OpenSSL):
rrreeeThese input data return the same plaintext in Java code!
Differences from your code:
Your code uses the deprecated mcrypt
. For security reasons, it should not be used now. A better alternative is PHP/OpenSSL, as shown in the code above. Furthermore, the implemented key derivation is wrong, e.g. it applies MD5 digest, which is not used at all in the Java code.
safety:
Although this may be an old app, a few notes on security:
build3DesKey()
is unsafe. If the key material is a string, it is usually not a key but a password. Therefore, a reliable key derivation function such as Argon2 or PBKDF2 should be used.