一个PHP带公钥加密类,很实用哦

Web交互安全一直是个各大网站的首要解决方案,本文介绍的PHP加密类非常实用哦,带有公钥,这是最大的亮点,没有公钥是不能解密的,加密度非常高。

看看Wiki介绍

公开密钥加密(英语:Public-key cryptography),也称为非对称加密(英语:asymmetric cryptography),是密碼學的一種演算法,它需要兩個密钥,一個是公開金鑰,另一個是私有密鑰;一個用作加密的時候,另一個則用作解密。使用其中一個密钥把明文加密后所得的密文,只能用相對應的另一個密钥才能解密得到原本的明文;甚至連最初用來加密的密鑰也不能用作解密。由於加密和解密需要兩個不同的密鑰,故被稱為非對稱加密;不同於加密和解密都使用同一個密鑰的對稱加密。雖然兩個密鑰在数学上相关,但如果知道了其中一个,并不能憑此计算出另外一个;因此其中一个可以公开,称为公钥,任意向外發佈;不公开的密钥为私钥,必須由用戶自行嚴格秘密保管,絕不透過任何途徑向任何人提供,也不會透露給要通訊的另一方,即使他被信任。

encryption.class.php

<?php
/**
 * PHP加密类
 * 琼台博客 www.qttc.net
 */
class Encryption{
  // 公钥
  protected $key = 'qttc'; 
  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;
  }
}

use.php

<?php
// 琼台博客 www.qttc.net

// 先包含加密类
require_once('encryption.class.php');

// 要加密的字符串
$string = 'https://www.qttc.net';

// 实例化加密类
$encryption = new Encryption();

// 设置公钥
$encryption->setKey('qttc');

// 加密字符串
$enc = $encryption->encrypt($string, $encryption->getPK);

// 解密字符串
$dec = $encryption->decrypt($enc, $encryption->getPK);

echo 'String: '.$string."\r\n";
echo 'Encrypted: '.$enc."\r\n";
echo 'Decoded: '.$dec."\r\n";

执行看看效果

[root@localhost php]# php use.php 
PHP Notice:  Undefined property: Encryption::$getPK in /root/php/use.php on line 15
PHP Notice:  Undefined property: Encryption::$getPK in /root/php/use.php on line 18
String: https://www.qttc.net
Encrypted: Z8Ttz#?PT-T$|{U{T#Z]z[clVgP)
Decoded: https://www.qttc.net

[root@localhost php]# php use.php 
String: https://www.qttc.net
Encrypted: mRrQ(Tu;Zu~U%r}Qt&Ur8SnXiz
Decoded: https://www.qttc.net

以上看出来,每一次的加密后的结果都不一样,但又能解密,单反

分享

TITLE: 一个PHP带公钥加密类,很实用哦

LINK: https://www.qttc.net/99-php-encryption.html

NOTE: 原创内容,转载请注明出自琼台博客