1, Foreword: The Project to access the third party payment encountered 3DES encryption, has not been used before, searched a lot of, are not applicable, all kinds of wrong, and later their combined search finally got the correct, the detection address: http://tool.chacuo.net/crypt3des.
2, the following is the class applicable (CBC encryption mode, pkcs5padding padding )
Code:
/**
* @des 3DES encryption algorithm, CBC mode, pkcs5padding character Fill method
*/
Class Tdea
{
/**
* @param string $crypt strings that need to be encrypted
* @param string $key The key used for encryption
* @param string $vi the vector used for encryption
* @return String $crypt encrypted
* @des 3DES Encryption
*/
Final static public function encrypt ($input, $key, $iv, $base = True) {
$size = 8;
$input = self::p kcs5_pad ($input, $size);
$encryption _descriptor = Mcrypt_module_open (Mcrypt_3des, ', ' CBC ', ');
Mcrypt_generic_init ($encryption _descriptor, $key, $IV);
$data = Mcrypt_generic ($encryption _descriptor, $input);
Mcrypt_generic_deinit ($encryption _descriptor);
Mcrypt_module_close ($encryption _descriptor);
Return Base64_encode ($data);
}
/**
* @param string $crypt strings that need to be decrypted
* @param string $key The key used for encryption
* @param string $vi the vector used for encryption
* @return String $input decrypted
* @des 3DES Decryption
*/
Final static public function decrypt ($crypt, $key, $iv, $base = True) {
$crypt = Base64_decode ($crypt);
$encryption _descriptor = Mcrypt_module_open (Mcrypt_3des, ', ' CBC ', ');
Mcrypt_generic_init ($encryption _descriptor, $key, $IV);
$decrypted _data = mdecrypt_generic ($encryption _descriptor, $crypt);
Mcrypt_generic_deinit ($encryption _descriptor);
Mcrypt_module_close ($encryption _descriptor);
$decrypted _data = self::p kcs5_unpad ($decrypted _data);
return RTrim ($decrypted _data);
}
Final static Private Function Pkcs5_pad ($text, $blocksize) {
$pad = $blocksize-(strlen ($text)% $blocksize);
Return $text. Str_repeat (Chr ($pad), $pad);
}
Final static Private Function Pkcs5_unpad ($text) {
$pad = Ord ($text {strlen ($text)-1});
if ($pad > strlen ($text)) {
return false;
}
Return substr ($text, 0,-1 * $pad);
}
}
Call Test
$plaintext = "3DES encryption test";
$key = "r0uscmduh5flo37ajv2fn72j";//key required for encryption
$iv = "1EX24DCE";//initialization vector
$ciphertext = Tdea::encrypt ($plaintext, $key, $IV);//encryption
$plaintext 2 = Tdea::d ecrypt ($ciphertext, $key, $IV);//decryption
echo "<b>String:</b> $plaintext <br><br>";
echo "<b>Encrypted:</b>";
Echo $ciphertext;
echo "<br><br><b>Decrypt:</b>";
echo $plaintext 2;
Detection address: Http://tool.chacuo.net/crypt3des
PHP 3DES plus decryption (CBC mode, pkcs5padding padding)