Re: Encrypt data...
| From: | Scott Fletcher | Date: | Thu, 26 Sep 2002 12:40:52 +0000 |
| Subject: | Re: Encrypt data... | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-117705@lists.php.net to get a copy of this message | ||
Aww! Neat! That look better than the one I came up with. Thanks for your
time on this one.
Thanks,
FletchSOD
"Tom Rogers" <trogers@kwikin.com> wrote in message
news:24214224788.20020926115359@kwikin.com...
> Hi,
>
> Thursday, September 26, 2002, 4:45:04 AM, you wrote:
> SF> How do I encrypt the data and decrypt it back using PHP? I do know
that hte
> SF> random number can not be used becuase it will make it impossible to
decrypt
> SF> it.
>
> SF> Thanks!
>
> Here is a simple class for encoding and decoding:
>
> class encrypt_class{
> var $secret;
> function encrypt_class(){
> $this->secret = 'this is a very long key, even too long
for the cipher';
> }
> Function encode($id){
> $eid = $iv = 0;
> $len = strlen($id);
> $id = $len.'-'.$id;
> $td = mcrypt_module_open(MCRYPT_TripleDES, "",
MCRYPT_MODE_ECB, "");
> $key = substr($this->secret, 0, mcrypt_enc_get_key_size
($td));
> $iv = pack("a".mcrypt_enc_get_iv_size($td),$iv);
> mcrypt_generic_init ($td, $key, $iv);
> $eid = base64_encode(mcrypt_generic ($td, $id));
> mcrypt_generic_deinit($td);
> return $eid;
> }
> Function decode($eid){
> $id = $iv = 0;
> $td = mcrypt_module_open (MCRYPT_TripleDES, "",
MCRYPT_MODE_ECB, "");
> $key = substr($this->secret, 0, mcrypt_enc_get_key_size
($td));
> $iv = pack("a".mcrypt_enc_get_iv_size($td),$iv);
> mcrypt_generic_init ($td, $key, $iv);
> $id = mdecrypt_generic ($td, base64_decode($eid));
> $len = strtok($id,'-');
> $id = substr($id,(strlen($len)+1),$len);
> mcrypt_generic_deinit($td);
> return $id;
> }
> }
>
>
> Usage
>
> <?
> $word = 'Hello';
> $e = new encrypt_class();
> $encrypted = $e->encode($word);
> echo "encrypted = $encrypted <br>";
> $decrypted = $e->decode($encrypted);
> echo "decrypted = $decrypted <br>";
> if($word == $decrypted){
> echo "They match <br>";
> }
> else{
> echo "Oops they don't match <br>";
> }
> <?
> --
> regards,
> Tom
>