3des encryption code in php (fully compatible with. net)

Source: Internet
Author: User

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 );
}
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.