PHP加密算法

加密概要

密碼學中,加密(英語:Encryption)是將明文信息改變爲難以讀取的密文內容,使之不可讀的過程。只有擁有解密方法的對象,經由解密過程,才能將密文還原爲正常可讀的內容。php

加密技術的重點是加密算法,加密算法主要分爲三類:算法

  1. 對稱加密
  2. 非對稱加密
  3. 不可逆加密

對稱加密算法

  1. 加密過程:數組

    • 將明文分紅N個組,而後對各個組進行加密,造成各自的密文,最後把全部的分組密文進行合併,造成最終的密文。
  2. 優勢:安全

    • 算法公開、計算量小、加密速度快、加密效率高
  3. 缺點:bash

    • 交易雙方都使用一樣鑰匙,安全性得不到保證
    • 密鑰管理困難,尤爲是在分佈式網絡中
  4. 經常使用算法:網絡

    • DES、3DES(TripleDES)、AES、RC二、RC四、RC5和Blowfish

PHP中對稱加密算法

$cipher_list = mcrypt_list_algorithms();//mcrypt支持的加密算法列表
$mode_list = mcrypt_list_modes();//mcrypt支持的加密模式列表

// print_r($cipher_list);
// print_r($mode_list);

function encrypt($key,$data){
    $td = mcrypt_module_open("des", "", "ecb", "");//使用MCRYPT_DES算法,ecb模式
    $size = mcrypt_enc_get_iv_size($td);       //設置初始向量的大小
    $iv = mcrypt_create_iv($size,MCRYPT_RAND); //建立初始向量

    $key_size = mcrypt_enc_get_key_size($td);       //返回所支持的最大的密鑰長度(以字節計算)
    $salt = '';
    $subkey = substr(md5(md5($key).$salt), 0,$key_size);//對key複雜處理,並設置長度

    mcrypt_generic_init($td, $subkey, $iv);
    $endata = mcrypt_generic($td, $data);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $endata;
}

function decrypt($key,$endata){
    $td = mcrypt_module_open("des", "", "ecb", "");//使用MCRYPT_DES算法,ecb模式
    $size = mcrypt_enc_get_iv_size($td);       //設置初始向量的大小
    $iv = mcrypt_create_iv($size,MCRYPT_RAND); //建立初始向量
    $key_size = mcrypt_enc_get_key_size($td);       //返回所支持的最大的密鑰長度(以字節計算)
    $salt = '';
    $subkey = substr(md5(md5($key).$salt), 0,$key_size);//對key複雜處理,並設置長度
    mcrypt_generic_init($td, $subkey, $iv);
    $data = rtrim(mdecrypt_generic($td, $endata)).'\n';
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $data;
}


$key = "www.tencent.com";
// $data = "返回所支持的最大的密鑰長度(涉及到發件費啦";
$data = "dadfafdafd,我是一個好孩子";

$endata =  encrypt($key,$data);

$data1 = decrypt($key,$endata);

echo $endata; //直接輸出,在網頁上是亂碼,用base64_encode處理,就變成由字符、數組、加號、斜槓等共64種字符註冊
echo base64_encode($endata);
echo $data1;
複製代碼

非對稱加密算法

  1. 使用過程:
    1. 乙方生成兩把密鑰(公鑰和私鑰)
    2. 甲方獲取乙方的公鑰,而後用它對信息加密。
    3. 乙方獲得加密後的信息,用私鑰解密,乙方也可用私鑰加密字符串
    4. 甲方獲取乙方私鑰加密數據,用公鑰解密
  2. 優勢:
    • 更安全,密鑰越長,它就越難破解
  3. 缺點:
    • 加密速度慢
  4. 經常使用算法:
    • RSA、Elgamal、揹包算法、Rabin、D-H、ECC(橢圓曲線加密算法) ####RSA算法
<?php
/**
 * 使用openssl實現非對稱加密
 */
class Rsa {
    /**
     * private key
     */
    private $_privKey;
    /**
     * public key
     */
    private $_pubKey;
    /**
     * the keys saving path
     */
    private $_keyPath;
    /**
     * the construtor,the param $path is the keys saving path
     */
    public function __construct($path) {
        if (empty($path) || !is_dir($path)) {
            throw new Exception('Must set the keys save path');
        }
        $this->_keyPath = $path;
    }
    /**
     * create the key pair,save the key to $this->_keyPath
     * 也可使用openssl命令生成公鑰私鑰
     *  openssl genrsa -out rsa_private_key.pem 1024
     *  openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
     */
    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:我是老鱉<br />';
$pre = $rsa->privEncrypt('我是老鱉');
echo 'private encrypted:<br />' . $pre . '<br />';
$pud = $rsa->pubDecrypt($pre);
echo 'public decrypted:' . $pud . '<br />';
//公鑰加密,私鑰解密
echo 'source:幹IT的<br />';
$pue = $rsa->pubEncrypt('幹IT的');
echo 'public encrypt:<br />' . $pue . '<br />';
$prd = $rsa->privDecrypt($pue);
echo 'private decrypt:' . $prd;
?>  
複製代碼

不可逆加密算法

加密過程當中不須要使用密鑰,輸入明文後由系統直接通過加密算法處理成密文,這種加密後的數據是沒法被解密的,只有從新輸入明文,並再次通過一樣不可逆的加密算法處理,獲得相同的加密密文並被系統從新識別後,才能真正解密。 經常使用算法有 md5, crypt,sha1分佈式

  1. md5
<?php
$data = 'hello';
echo md5($data); //輸出32位的16進制 5d41402abc4b2a76b9719d911017c592
複製代碼
  1. crypt
//以不一樣散列類型使用 crypt()
<?php
if (CRYPT_STD_DES == 1) {
    echo 'Standard DES: ' . crypt('rasmuslerdorf', 'rl') . "\n";
}

if (CRYPT_EXT_DES == 1) {
    echo 'Extended DES: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
}

if (CRYPT_MD5 == 1) {
    echo 'MD5: ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
}

if (CRYPT_BLOWFISH == 1) {
    echo 'Blowfish: ' . crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA256 == 1) {
    echo 'SHA-256: ' . crypt('rasmuslerdorf', '$5$rounds=5000$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA512 == 1) {
    echo 'SHA-512: ' . crypt('rasmuslerdorf', '$6$rounds=5000$usesomesillystringforsalt$') . "\n";
}
?>

以上輸出
Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:          $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish:     $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256:      $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512:      $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
複製代碼
  1. sha1
<?php
$data="hello";
echo sha1($data); // aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
//固然,能夠將多種加密算法混合使用
echo md5(sha1($data));
//輸出:e69d7e620e82be5eb414d1f8d1d4b9d9
//這種方式的雙重加密也能夠提升數據的安全性
複製代碼
相關文章
相關標籤/搜索