PHP 基礎篇 - PHP 中 DES 加解密詳解


一、簡介

DES 是對稱性加密里面常見一種,全稱為 Data Encryption Standard,即數據加密標准,是一種使用密鑰加密的塊算法。密鑰長度是64位(bit),超過位數密鑰被忽略。所謂對稱性加密即加密和解密密鑰相同,對稱性加密一般會按照固定長度,把待加密字符串分成塊,不足一整塊或者剛好最后有特殊填充字符。

跨語言做 DES 加密解密經常會出現問題,往往是填充方式不對、編碼不一致或者加密解密模式沒有對應上造成。常見的填充模式有: pkcs5、pkcs7、iso10126、ansix923、zero。加密模式有:DES-ECB、DES-CBC、DES-CTR、DES-OFB、DES-CFB。

作為一個軟件開發者,可以通過工具測試 DES 加密解密,這里推薦一個在線工具:http://tool.chacuo.net/cryptdes

二、實現

PHP 提供了 Mcrypt 系列函數來實現 DES 的加解密,但該擴展中的函數陸續被廢棄,自 PHP 7.2.0 起,會移到 PECL。

所以本代碼用了更通用的 OPENSSL 方式實現 DES 的加解密,具體的實現和使用代碼如下:

<?php

/**
 * openssl 實現的 DES 加密類,支持各種 PHP 版本
 */
class DES
{
    /**
     * @var string $method 加解密方法,可通過 openssl_get_cipher_methods() 獲得
     */
    protected $method;

    /**
     * @var string $key 加解密的密鑰
     */
    protected $key;

    /**
     * @var string $output 輸出格式 無、base64、hex
     */
    protected $output;

    /**
     * @var string $iv 加解密的向量
     */
    protected $iv;

    /**
     * @var string $options
     */
    protected $options;

    // output 的類型
    const OUTPUT_NULL = '';
    const OUTPUT_BASE64 = 'base64';
    const OUTPUT_HEX = 'hex';


    /**
     * DES constructor.
     * @param string $key
     * @param string $method
     *      ECB DES-ECB、DES-EDE3 (為 ECB 模式時,$iv 為空即可)
     *      CBC DES-CBC、DES-EDE3-CBC、DESX-CBC
     *      CFB DES-CFB8、DES-EDE3-CFB8
     *      CTR
     *      OFB
     *
     * @param string $output
     *      base64、hex
     *
     * @param string $iv
     * @param int $options
     */
    public function __construct($key, $method = 'DES-ECB', $output = '', $iv = '', $options = OPENSSL_RAW_DATA | OPENSSL_NO_PADDING)
    {
        $this->key = $key;
        $this->method = $method;
        $this->output = $output;
        $this->iv = $iv;
        $this->options = $options;
    }

    /**
     * 加密
     *
     * @param $str
     * @return string
     */
    public function encrypt($str)
    {
        $str = $this->pkcsPadding($str, 8);
        $sign = openssl_encrypt($str, $this->method, $this->key, $this->options, $this->iv);

        if ($this->output == self::OUTPUT_BASE64) {
            $sign = base64_encode($sign);
        } else if ($this->output == self::OUTPUT_HEX) {
            $sign = bin2hex($sign);
        }

        return $sign;
    }

    /**
     * 解密
     *
     * @param $encrypted
     * @return string
     */
    public function decrypt($encrypted)
    {
        if ($this->output == self::OUTPUT_BASE64) {
            $encrypted = base64_decode($encrypted);
        } else if ($this->output == self::OUTPUT_HEX) {
            $encrypted = hex2bin($encrypted);
        }

        $sign = @openssl_decrypt($encrypted, $this->method, $this->key, $this->options, $this->iv);
        $sign = $this->unPkcsPadding($sign);
        $sign = rtrim($sign);
        return $sign;
    }

    /**
     * 填充
     *
     * @param $str
     * @param $blocksize
     * @return string
     */
    private function pkcsPadding($str, $blocksize)
    {
        $pad = $blocksize - (strlen($str) % $blocksize);
        return $str . str_repeat(chr($pad), $pad);
    }

    /**
     * 去填充
     * 
     * @param $str
     * @return string
     */
    private function unPkcsPadding($str)
    {
        $pad = ord($str{strlen($str) - 1});
        if ($pad > strlen($str)) {
            return false;
        }
        return substr($str, 0, -1 * $pad);
    }

}


$key = 'key123456';
$iv = 'iv123456';

// DES CBC 加解密
$des = new DES($key, 'DES-CBC', DES::OUTPUT_BASE64, $iv);
echo $base64Sign = $des->encrypt('Hello DES CBC');
echo "\n";
echo $des->decrypt($base64Sign);
echo "\n";

// DES ECB 加解密
$des = new DES($key, 'DES-ECB', DES::OUTPUT_HEX);
echo $base64Sign = $des->encrypt('Hello DES ECB');
echo "\n";
echo $des->decrypt($base64Sign);

三、相關鏈接


本文首發於馬燕龍個人博客,歡迎分享,轉載請標明出處。
馬燕龍個人博客:http://www.mayanlong.com
馬燕龍個人微博:http://weibo.com/imayanlong
馬燕龍Github主頁:https://github.com/yanlongma


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM