This is the PHP equivalent of your Java code (I copied PKCS # 5-padding from a comment 20-Sep-2006 07:56 mcrypt link )
function encryptText($plainText, $key) { $keyData = "\xA2\x15\x37\x08\xCA\x62\xC1\xD2" . "\xF7\xF1\x93\xDF\xD2\x15\x4F\x79\x06" . "\x67\x7A\x82\x94\x16\x32\x95"; $padded = pkcs5_pad($plainText, mcrypt_get_block_size("tripledes", "cbc")); $encText = mcrypt_encrypt("tripledes", $keyData, $padded, "cbc", $key); return base64_encode($encText); } function decryptText($encryptText, $key) { $keyData = "\xA2\x15\x37\x08\xCA\x62\xC1\xD2" . "\xF7\xF1\x93\xDF\xD2\x15\x4F\x79\x06" . "\x67\x7A\x82\x94\x16\x32\x95"; $cipherText = base64_decode($encryptText); $res = mcrypt_decrypt("tripledes", $keyData, $cipherText, "cbc", $key); $resUnpadded = pkcs5_unpad($res); return $resUnpadded; } function pkcs5_pad ($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } function pkcs5_unpad($text) { $pad = ord($text{strlen($text)-1}); if ($pad > strlen($text)) return false; if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false; return substr($text, 0, -1 * $pad); }
But there are some issues you should be aware of:
- In Java code, you call
String.getBytes() without specifying an encoding. This makes your code not portable if your plain text contains non-ASCII characters, such as umlauts, because Java uses the default character set. If you can change this, I would do it. I recommend using utf-8 on both sides (Java and PHP). - You have a hard-coded encryption key and use IV as the "key". I'm by no means a crypto expert, but for me he just feels wrong and can open up a huge security leak.
- Create a random IV and simply connect it at the beginning or at the end of your message. Since the size of IV is equal to AFAIK, equal to the block size of your cipher, you simply delete as many bytes from the beginning or end and easily separate IV from the message.
- As for the key, it is best to use some method to generate the key with the correct size from "human-generated human". "
Of course, if you need to fulfill some of the specified requirements, you will not be able to change your method.
source share