淺談 PHP 中的多種加密技術及程式碼範例

來源:互聯網
上載者:User
同樣是一道面試答錯的問,面試官問我非對稱式加密演算法中有哪些經典的演算法? 當時我愣了一下,因為我把非對稱式加密與單項散列加密的概念弄混淆了,所以更不用說什麼非對稱式加密演算法中有什麼經典演算法,結果當然也讓面試官愣了一下,所以今天就花點時間說說PHP中的資訊加密技術

資訊加密技術的分類

單項散列加密技術(無法復原的加密)

屬於摘要演算法,不是一種密碼編譯演算法,作用是把任意長的輸入字串變化成固定長的輸出串的一種函數

MD5

string md5 ( string $str [, bool $raw_output = false ] ); //MD5加密,輸入任意長度字串返回一個唯一的32位字元

md5()為單向加密,沒有逆向解密演算法,但是還是可以對一些常見的字串通過收集,枚舉,碰撞等方法破解;所以為了讓其破解起來更麻煩一些,所以我們一般加一點鹽值(salt)並雙重MD5;

md5(md5($password).'sdva');

sdva就是鹽值,該鹽值應該是隨機的,比如md5常用在密碼加密上,所以在註冊的時候我會隨機產生這個字串,然後通過上面的方法來雙重加密一下;

Crypt

很少看到有人用這個函數,如果要用的話有可能是用在對稱或非對稱的演算法裡面,瞭解一下既可;

string crypt ( string $str [, string $salt ] ) //第一個為需要加密的字串,第二個為鹽值(就是加密幹擾值,如果沒有提供,則預設由PHP自動產生);返回散列後的字串或一個少於 13 字元的字串,後者為了區別鹽值

   

非對稱式加密

非對稱式加密演算法需要兩個密鑰來進行加密和解密,這兩個秘鑰是公開密鑰(public key,簡稱公開金鑰)和私人密鑰(private key,簡稱私密金鑰);

,甲乙之間使用非對稱式加密的方式完成了重要訊息的安全傳輸。

  1. 乙方產生一對密鑰(公開金鑰和私密金鑰)並將公開金鑰向其它方公開。

  2. 得到該公開金鑰的甲方使用該金鑰組機密資訊進行加密後再發送給乙方。

  3. 乙方再用自己儲存的另一把專用密鑰(私密金鑰)對加密後的資訊進行解密。乙方只能用其專用密鑰(私密金鑰)解密由對應的公開金鑰加密後的資訊。

在傳輸過程中,即使攻擊者截獲了傳輸的密文,並得到了乙的公開金鑰,也無法破解密文,因為只有乙的私密金鑰才能解密密文
同樣,如果乙要回複加密資訊給甲,那麼需要甲先公布甲的公開金鑰給乙用於加密,甲自己儲存甲的私密金鑰用於解密。

在非對稱式加密中使用的主要演算法有:RSA、Elgamal、背包演算法、Rabin、D-H、ECC(橢圓曲線密碼編譯演算法)等。 其中我們最見的演算法是RSA演算法

以下是從網上摘抄的一段PHP通過openssl實現非對稱式加密的演算法

_keyPath = $path;     }     /**      * create the key pair,save the key to $this->_keyPath      */     public function createKey() {         $r = openssl_pkey_new();         openssl_pkey_export($r, $privKey);         file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . 'priv.key', $privKey);         $this->_privKey = openssl_pkey_get_public($privKey);         $rp = openssl_pkey_get_details($r);         $pubKey = $rp['key'];         file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . 'pub.key', $pubKey);         $this->_pubKey = openssl_pkey_get_public($pubKey);     }     /**      * setup the private key      */     public function setupPrivKey() {         if (is_resource($this->_privKey)) {             return true;         }         $file = $this->_keyPath . DIRECTORY_SEPARATOR . 'priv.key';         $prk = file_get_contents($file);         $this->_privKey = openssl_pkey_get_private($prk);         return true;     }     /**      * setup the public key      */     public function setupPubKey() {         if (is_resource($this->_pubKey)) {             return true;         }         $file = $this->_keyPath . DIRECTORY_SEPARATOR . 'pub.key';         $puk = file_get_contents($file);         $this->_pubKey = openssl_pkey_get_public($puk);         return true;     }     /**      * encrypt with the private key      */     public function privEncrypt($data) {         if (!is_string($data)) {             return null;         }         $this->setupPrivKey();         $r = openssl_private_encrypt($data, $encrypted, $this->_privKey);         if ($r) {             return base64_encode($encrypted);         }         return null;     }     /**      * decrypt with the private key      */     public function privDecrypt($encrypted) {         if (!is_string($encrypted)) {             return null;         }         $this->setupPrivKey();         $encrypted = base64_decode($encrypted);         $r = openssl_private_decrypt($encrypted, $decrypted, $this->_privKey);         if ($r) {             return $decrypted;         }         return null;     }     /**      * encrypt with public key      */     public function pubEncrypt($data) {         if (!is_string($data)) {             return null;         }         $this->setupPubKey();         $r = openssl_public_encrypt($data, $encrypted, $this->_pubKey);         if ($r) {             return base64_encode($encrypted);         }         return null;     }     /**      * decrypt with the public key      */     public function pubDecrypt($crypted) {         if (!is_string($crypted)) {             return null;         }         $this->setupPubKey();         $crypted = base64_decode($crypted);         $r = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey);         if ($r) {             return $decrypted;         }         return null;     }     public function __destruct() {         @fclose($this->_privKey);         @fclose($this->_pubKey);     } } //以下是一個簡單的測試demo,如果不需要請刪除 $rsa = new Rsa('ssl-key'); //私密金鑰加密,公開金鑰解密 echo 'source:我是老鱉
'; $pre = $rsa->privEncrypt('我是老鱉'); echo 'private encrypted:
' . $pre . '
'; $pud = $rsa->pubDecrypt($pre); echo 'public decrypted:' . $pud . '
'; //公開金鑰加密,私密金鑰解密 echo 'source:幹IT的
'; $pue = $rsa->pubEncrypt('幹IT的'); echo 'public encrypt:
' . $pue . '
'; $prd = $rsa->privDecrypt($pue); echo 'private decrypt:' . $prd; ?>

對稱式加密演算法

對稱式加密(也叫私密金鑰加密)指加密和解密使用相同密鑰的密碼編譯演算法。有時又叫傳統密碼演算法,就是加密金鑰能夠從解密密鑰中推算出來,同時解密密鑰也可以 從加密金鑰中推算出來。而在大多數的對稱演算法中,加密金鑰和解密密鑰是相同的,所以也稱這種密碼編譯演算法為秘密密鑰演算法或單密鑰演算法。它要求發送方和接收方在 安全通訊之前,商定一個密鑰。對稱演算法的安全性依賴於密鑰,泄漏密鑰就意味著任何人都可以對他們發送或接收的訊息解密,所以密鑰的保密性對通訊性至關重 要。

對稱式加密的常用演算法有: DES演算法,3DES演算法,TDEA演算法,Blowfish演算法,RC5演算法,IDEA演算法

在PHP中也有封裝好的對稱式加密函數

Urlencode/Urldecode  string urlencode ( string $str ) /* 1. 一個參數,傳入要加密的字串(通常應用於對URL的加密) 2. urlencode為雙向加密,可以用urldecode來加密(嚴格意義上來說,不算真正的加密,更像是一種編碼方式) 3. 返回字串,此字串中除了 -_. 之外的所有非字母數字字元都將被替換成百分比符號(%)後跟兩位十六進位數,空格則編碼為加號(+)。 */

通過Urlencode函數解決連結中帶有&字元引起的問:

 zhou   [gang] =>   [password] => zhou ) */  //如下解決問: $username="zhou&gang"; $url_decode="zhougang.com?username=".urlencode($username)."&password=zhou"; ?>  常見的urlencode()的轉換字元  ?=> %3F = => %3D % => %25 & => %26 \ => %5C  base64  string base64_decode ( string $encoded_data )      base64_encode()接受一個參數,也就是要編碼的資料(這裡不說字串,是因為很多時候base64用來編碼圖片)      base64_encode()為雙向加密,可用base64_decode()來解密  $data=file_get_contents($filename); echo base64_encode($data); /*然後你查看網頁源碼就會得到一大串base64的字串, 再用base64_decode()還原就可以得到圖片。這也可以作為移動端上傳圖片的處理方案之一(但是不建議這樣做哈) */

嚴格的來說..這兩個函數其實不算是加密,更像是一種格式的序列化

以下是我們PHP程式中常用到的對稱式加密演算法

discuz經典演算法

 0) &&  substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {               return substr($result, 26);           } else {               return '';           }       } else {           // 把動態密匙儲存在密文裡,這也是為什麼同樣的明文,生產不同密文後能解密的原因           // 因為加密後的密文可能是一些特殊字元,複製過程可能會丟失,所以用base64編碼           return $keyc.str_replace('=', '', base64_encode($result));       }   }

加解密函數encrypt()

               
  
  1. //$string:需要加密解密的字串;$operation:判斷是加密還是解密,E表示加密,D表示解密;$key:密匙

  2. function encrypt($string,$operation,$key=''){

  3. $key=md5($key);

  4. $key_length=strlen($key);

  5. $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;

  6. $string_length=strlen($string);

  7. $rndkey=$box=array();

  8. $result='';

  9. for($i=0;$i<=255;$i++){

  10. $rndkey[$i]=ord($key[$i%$key_length]);

  11. $box[$i]=$i;

  12. }

  13. for($j=$i=0;$i<256;$i++){

  14. $j=($j+$box[$i]+$rndkey[$i])%256;

  15. $tmp=$box[$i];

  16. $box[$i]=$box[$j];

  17. $box[$j]=$tmp;

  18. }

  19. for($a=$j=$i=0;$i<$string_length;$i++){

  20. $a=($a+1)%256;

  21. $j=($j+$box[$a])%256;

  22. $tmp=$box[$a];

  23. $box[$a]=$box[$j];

  24. $box[$j]=$tmp;

  25. $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));

  26. }

  27. if($operation=='D'){

  28. if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){

  29. return substr($result,8);

  30. }else{

  31. return'';

  32. }

  33. }else{

  34. return str_replace('=','',base64_encode($result));

  35. }

  36. }

  37. ?>

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.