<?php Class Crypt3des { var $key; function Crypt3des ($key) { $this->key = $key; } Function Encrypt ($input) { $size = mcrypt_get_block_size (mcrypt_3des, ' ECB '); $input = $this->pkcs5_pad ($ input, $size); $key = Str_pad ($this->key,24, ' 0 '); $td = Mcrypt_module_open (Mcrypt_3des, ', ' ECB ', '); $iv = @mcrypt_create_iv (Mcrypt_enc_get_iv_size ($TD), Mcrypt_rand); @mcrypt_generic_init ($TD, $key, $IV); $data = Mcrypt_generic ($TD, $input); Mcrypt_generic_deinit ($TD); Mcrypt_module_close ($TD); //$data = Base64_encode ($this->paddingpkcs7 ($data)); $data = Base64_encode ($data); return $data; } function Decrypt ($encrypted) { $encrypted = Base64_decode ($encrypted); $key = Str_pad ($this->key,24, ' 0 '); $TD = Mcrypt_module_open (Mcrypt_3des, ', ' ECB ', '); $iv = @mcrypt_create_iv (Mcrypt_enc_get_iv_size ($TD), Mcrypt_rand); $ks = Mcrypt_enc_get_key_size ($TD); @mcrypt_generic_init ($TD, $key, $IV); $decrypted = Mdecrypt_generic ($TD, $encrypted); Mcrypt_generic_deinit ($TD); Mcrypt_module_close ($TD); $y = $this->pkcs5_unpad ($decrypted); return $y; } 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); } function PaddingPKCS7 ($data) { $block _size = mcrypt_get_block_size (Mcrypt_3des, MCRYPT_MODE_CBC); $padding _char = $block _size-(strlen ($data)% $block _size); $data. = Str_repeat (Chr ($padding _char), $padding _char); return $data; } } Usage: $crypt = new Crypt3des (' key '); $a = ' to encrypt string '; $code = $crypt->encrypt ($a);//encryption echo $crypt->decrypt ($code);//Decrypt |