PHP encryption and decryption class implementation code

Source: Internet
Author: User
Tags crypt decrypt md5 strlen

Class crypt{

This article source: Dragon elder brother Blog

protected $key = ""; Public

Private function keyed ($txt, $encrypt _key)

{

$encrypt _key = MD5 ($encrypt _key);

$ctr = 0;

$tmp = "";

for ($i =0; $i

{

if ($ctr ==strlen ($encrypt _key)) {

$ctr = 0;

}

$tmp. = substr ($txt, $i, 1) ^ substr ($encrypt _key, $ctr, 1);

$ctr + +;

}

return $tmp;

}

Public function Encrypt ($txt, $key = "")

{

if (empty ($key)) {

$key = $this->key;

}

Srand (Double) microtime () *1000000);

$encrypt _key = MD5 (rand (0,32000));

$ctr = 0;

$tmp = "";

for ($i =0; $i

{

if ($ctr ==strlen ($encrypt _key)) {

$ctr = 0;

}

$tmp. = substr ($encrypt _key, $ctr, 1).

(Substr ($txt, $i, 1) ^ substr ($encrypt _key, $ctr, 1));

$ctr + +;

}

return $this->keyed ($tmp, $key);

}

Public function Decrypt ($txt, $key = "")

{

if (empty ($key)) {

$key = $this->key;

}

$txt = $this->keyed ($txt, $key);

$tmp = "";

for ($i =0; $i

{

$MD 5 = substr ($txt, $i, 1);

$i + +;

$tmp. = (substr ($txt, $i, 1) ^ $md 5);

}

return $tmp;

}

Public Function Setkey ($key)

{

if (empty ($key)) {

return null;

}

$this->key= $key;

}

Public Function Getkey ()

{

return $this->key;

}

Downloads by http://www.veryhuo.com

}

$string = "http://www.52blogger.com";

$crypt = new Crypt ();

$crypt->setkey ("http://www.52blogger.com");

$enc _text = $crypt->encrypt ($string, $crypt->getkey ());

$dec _text = $crypt->decrypt ($enc _text, $crypt->getkey ());

echo Before encryption: $string

n ";

echo after encryption: $enc _text

n ";

echo "After decryption: $dec _text n";

?>

Execution results:

Pre-encryption: http://www.52blogger.com

After encryption: Hszq ' z* kp~y (Wpvs=6q3gzbr5qkhtz (f=zm

After decryption: http://www.52blogger.com

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.