Copy codeThe Code is as follows:
<? Php
Class Crypt3Des
{
Private $ key = "";
Private $ iv = "";
/**
* Construct and pass two keys and IV that have been base64_encode
*
* @ Param string $ key
* @ Param string $ iv
*/
Function _ construct ($ key, $ iv)
{
If (empty ($ key) | empty ($ iv )){
Echo 'key and iv is not valid ';
Exit ();
}
$ This-> key = $ key;
$ This-> iv = $ iv;
}
/**
* Encryption
* @ Param <type> $ value
* @ Return <type>
*/
Public function encrypt ($ value)
{
$ Td = mcrypt_module_open (MCRYPT_3DES, '', MCRYPT_MODE_CBC ,'');
$ Iv = base64_decode ($ this-> iv );
$ Value = $ this-> PaddingPKCS7 ($ value );
$ Key = base64_decode ($ this-> key );
Mcrypt_generic_init ($ td, $ key, $ iv );
$ Ret = base64_encode (mcrypt_generic ($ td, $ value ));
Mcrypt_generic_deinit ($ td );
Mcrypt_module_close ($ td );
Return $ ret;
}
/**
* Decryption
* @ Param <type> $ value
* @ Return <type>
*/
Public function decrypt ($ value)
{
$ Td = mcrypt_module_open (MCRYPT_3DES, '', MCRYPT_MODE_CBC ,'');
$ Iv = base64_decode ($ this-> iv );
$ Key = base64_decode ($ this-> key );
Mcrypt_generic_init ($ td, $ key, $ iv );
$ Ret = trim (mdecrypt_generic ($ td, base64_decode ($ value )));
$ Ret = $ this-> UnPaddingPKCS7 ($ ret );
Mcrypt_generic_deinit ($ td );
Mcrypt_module_close ($ td );
Return $ ret;
}
Private function PaddingPKCS7 ($ data)
{
$ Block_size = mcrypt_get_block_size ('tripledes ', 'cbc ');
$ Padding_char = $ block_size-(strlen ($ data) % $ block_size );
$ Data. = str_repeat (chr ($ padding_char), $ padding_char );
Return $ data;
}
Private function UnPaddingPKCS7 ($ 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 );
}
}
?>