Web interaction security has always been a major site of the first solution, this article describes the PHP encryption class is very practical oh, with the public key, this is the biggest bright spot, no public key can not decrypt, add density is very high.
Class Code:
<?php/** * PHP Encryption class * Jones Taiwan Blog/class jiami{//Public key protected $key = ' Lee ';
Private function keyed ($txt, $encrypt _key) {$encrypt _key = MD5 ($encrypt _key);
$ctr = 0;
$tmp = ';
For ($i =0 $i <strlen ($txt); $i + +) {if ($ctr ==strlen ($encrypt _key)) {$ctr = 0;
$tmp. = substr ($txt, $i, 1) ^ substr ($encrypt _key, $ctr, 1);
$ctr + +;
return $tmp;
The 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 <strlen ($txt); $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);
The public function decrypt ($txt, $key = ') {if Empty ($key)) {$key = $this->key;
$txt = $this->keyed ($txt, $key); $tmp = ';
For ($i =0 $i <strlen ($txt); $i + +) {$MD 5 = substr ($txt, $i, 1);
$i + +;
$tmp. = (substr ($txt, $i, 1) ^ $md 5);
return $tmp;
The Public Function Setkey ($key) {if (empty ($key)) {return null;
} $this->key= $key;
The Public Function getpk () {return $this->key;
}
}
How to use:
<?php
///First include encryption class
require_once (' jiami.class.php ');
The string to encrypt
$string = ' http://www.jb51.net ';
Instantiate the cryptographic class
$jiami = new Jiami ();
Set Public key
$jiami->setkey (' QTTC ');
Encrypted string
$enc = $jiami->encrypt ($string, $jiami->getpk ());
Decrypt
the string $dec = $jiami->decrypt ($enc, $jiami->getpk ());
Echo ' <meta charset= ' utf-8 '/> ';
Echo ' Before encryption: '. $string. ' <br/> ';
Echo ' encrypted: '. $enc. ' <br/> ';
Echo ' after decryption: '. $dec;
? >
Page Execution Results
Result 1:
Result 2:
As can be seen from the above results, each encryption generated by the encryption string is different, this is random.
When decrypting, you need to use the public key when encrypting, or you cannot decrypt it. such as your encryption public key use ' QTTC ', decryption time, also need to use this ' QTTC ' as the public key to decrypt, otherwise cannot decrypt.