溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用PHP實現(xiàn)帶公鑰加密類

發(fā)布時間:2021-09-29 14:41:56 來源:億速云 閱讀:116 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了如何使用PHP實現(xiàn)帶公鑰加密類,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

類代碼:

<?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;
  }
 
}

使用方法:

<?php
// 先包含加密類
require_once('jiami.class.php');
 
// 要加密的字符串
$string = 'https://www.jb51.net';
 
// 實例化加密類
$jiami= new Jiami();
 
// 設(shè)置公鑰
$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;
?>

頁面執(zhí)行結(jié)果

結(jié)果1:

如何使用PHP實現(xiàn)帶公鑰加密類

結(jié)果2:

如何使用PHP實現(xiàn)帶公鑰加密類

由以上結(jié)果可以看到,每次加密產(chǎn)生的加密字符串都不一樣,這是隨機的。
解密的時候,需要使用加密時的公鑰,否則無法解密。如你這邊加密公鑰使用‘qttc',解密的時候,也需要使用這個'qttc'作為公鑰去解密,否則無法解密。

感謝你能夠認真閱讀完這篇文章,希望小編分享的“如何使用PHP實現(xiàn)帶公鑰加密類”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI