php DES 加密與解密詳解
本文介紹如何在PHP中實現DES加密和解密。 我們將基于一個已有的解密函數,構建完整的加密功能,并提供完整的代碼示例。
首先,我們分析給定的解密函數:
/** * 16進制轉字符串 * @param string $hex * @return string */ public function hextostr(string $hex) { $string = ""; for ($i = 0; $i < strlen($hex) - 1; $i += 2) { $string .= chr(hexdec($hex{$i} . $hex{$i + 1})); } return $string; } public function desDecrypt(string $str) { $key = "testkey"; // 密鑰 $base64 = base64_decode($this->hextostr($str)); return openssl_decrypt($base64, 'des-ecb', $key); }
基于此,我們創建一個類,包含加密和解密方法:
<?php class DES { private $key; public function __construct($key) { $this->key = $key; } /** * 字符串轉16進制 * @param string $str * @return string */ private function strToHex(string $str) { $hex = ''; for ($i = 0; $i < strlen($str); $i++) { $hex .= dechex(ord($str[$i])); } return $hex; } /** * 16進制轉字符串 * @param string $hex * @return string */ private function hexToStr(string $hex) { $string = ''; for ($i = 0; $i < strlen($hex) - 1; $i += 2) { $string .= chr(hexdec($hex{$i} . $hex{$i + 1})); } return $string; } /** * 加密 * @param string $str * @return string */ public function desEncrypt(string $str) { $base64 = openssl_encrypt($str, 'des-ecb', $this->key); return $this->strToHex($base64); } /** * 解密 * @param string $str * @return string */ public function desDecrypt(string $str) { $base64 = base64_decode($this->hexToStr($str)); return openssl_decrypt($base64, 'des-ecb', $this->key); } } $key = "testkey"; $des = new DES($key); $name = "123"; $encryptedName = $des->desEncrypt($name); echo "加密: " . $encryptedName . "n"; $decryptedName = $des->desDecrypt($encryptedName); echo "解密: " . $decryptedName . "n"; ?>
這段代碼定義了DES類,包含desEncrypt和desDecrypt方法分別用于加密和解密。 strToHex和hexToStr方法用于字符串和16進制字符串之間的轉換。 最后,我們用一個測試用例驗證了加密和解密的完整性。 請確保您的PHP環境已安裝OpenSSL擴展。 密鑰”testkey”僅用于示例,實際應用中請使用更安全的密鑰生成方法。
立即學習“PHP免費學習筆記(深入)”;
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END