PHP DES加密解密

來源:互聯網
上載者:User
這是一段 DES 解密的 PHP 代碼。

參考自 http://php.net/manual/zh/function.mcrypt-module-open.php 中的常式。 本來也 沒有什麼難的。

但是我 解密 完 後 反覆試,都是下面 這樣的不可見 的亂碼。

? ?]Y)?aw#?Y?????]m?/m?2??]C??f??V(?I?????~????? ?e=i"C??????


搞了大半天才 發現,是因為 對方 加密完之後 ,把二進位的 密文 轉換成 十六進位的 給我傳了過來 ,如13BD5122F55E706D13FB7D0F349A787D19E9D2334E268A15

大家看清楚啊, 這個可不能當作 密文本身 ,我就只因為 直接解密 這個 16進位的字串 所以才 無法解密的。 需要 先把這個 16進位的 字串 傳化 回 二進位的 模樣,再用 解密方法解密 ,就可以看到明文了 。

十六進位 轉 二進位 的方法 是hex2bin

cryptare 這個函數 是 加密解密用的 ,第一個參數是 明文或者密文, 第二個參數是key, 第三個參數 0 表示 解密,1就是 加密。

註: 加密的時候可能用不到 $text = $this->hex2bin($text); 這一句。


    function hex2bin($hexData)     {        $binData = "";        for($i = 0; $i < strlen ( $hexData ); $i += 2) {         $binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) );        }               return $binData;    }               function cryptare($text, $key, $crypt)     {         $text = $this->hex2bin($text);        $encrypted_data="";         $td = mcrypt_module_open('des', '', 'ecb', '');                         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);         mcrypt_generic_init($td, $key, $iv);         if($crypt)         {               $encrypted_data = mcrypt_generic($td, $text);         print $encrypted_data ;        }               else            {               $encrypted_data = mdecrypt_generic($td, $text);         }               mcrypt_generic_deinit($td);         mcrypt_module_close($td);         return $encrypted_data;     }
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.