WEB interaction security has always been the primary solution for major websites. The PHP encryption class introduced in this article is very practical. It comes with a public key, which is the biggest highlight. It cannot be decrypted without the public key, and the encryption density is very high.
Class code:
<?php /** * PHP加密类 * 琼台博客 */ class Jiami{ // 公钥 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; } 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); } public function decrypt($txt,$key=''){ if(empty($key)){ $key=$this->key; } $txt = $this->keyED($txt,$key); $tmp = ''; for ($i=0;$i<strlen($txt);$i++){ $md5 = substr($txt,$i,1); $i++; $tmp.= (substr($txt,$i,1) ^ $md5); } return $tmp; } public function setKey($key){ if(empty($key)){ return null; } $this->key=$key; } public function getPK(){ return $this->key; } }
Usage:
<?php // 先包含加密类 require_once('jiami.class.php'); // 要加密的字符串 $string = 'http://www.bkjia.com'; // 实例化加密类 $jiami= new Jiami(); // 设置公钥 $jiami->setKey('qttc'); // 加密字符串 $enc = $jiami->encrypt($string,$jiami->getPK()); // 解密字符串 $dec = $jiami->decrypt($enc,$jiami->getPK()); echo '<meta charset="utf-8" />'; echo '加密前 : '.$string .'<br/>'; echo '加密后 : '.$enc .'<br/>'; echo '解密后 : '.$dec; ?>
Page execution results
Result 1:
Result 2:
As you can see from the above results, the encrypted string generated by each encryption is different, which is random.
When decrypting, you need to use the public key used in encryption, otherwise it cannot be decrypted. If you use 'qttc' as the public key for encryption, you also need to use 'qttc' as the public key for decryption, otherwise it will not be possible to decrypt.
Symmetric encryption is faster than asymmetric encryption. The symmetric encryption key cannot be made public. The asymmetric private key must be kept secret. The public key can be made public. Management and release of symmetric encryption are more complicated. As for the algorithm, symmetric encryption usually uses DES, AES, and IDEA. Asymmetric using RSA
C. The encryption key and decryption key are the same