您的位置:首頁技術文章
文章詳情頁

PHP字符串和十六進制如何實現互相轉換

瀏覽:107日期:2022-09-09 15:34:19

今天在做項目中,因為要調用別人網站的接口,結果需要對請求和返回的時間進行十六進制加密處理,于是在網上查了下資料謝了一個轉換Demo做個記錄。

如果在TP下使用可以將下面函數放到common.php中

一,加密函數

<?php/** *字符串轉十六進制函數 *@pream string $str=’abc’; */function strToHex($str) { $hex = ''; for ($i = 0;$i < strlen($str);$i++) $hex.= dechex(ord($str[$i])); $hex = strtoupper($hex); return $hex;}?>

二、解密函數

<?php/** *十六進制轉字符串函數 *@pream string $hex=’616263’; */function hexToStr($hex) { $str = ''; for ($i = 0;$i < strlen($hex) - 1;$i+= 2) $str.= chr(hexdec($hex[$i] . $hex[$i + 1])); return $str;}?>

加密 解密 轉換 函數使用Demo事例,這里為了方便寫在了一個類中。

<?phpclass Test { /** *字符串轉十六進制函數 *@pream string $str=’abc’; */ public function strToHex($str) { $hex = ''; for ($i = 0;$i < strlen($str);$i++) $hex.= dechex(ord($str[$i])); $hex = strtoupper($hex); return $hex; } /** *十六進制轉字符串函數 *@pream string $hex=’616263’; */ public function hexToStr($hex) { $str = ''; for ($i = 0;$i < strlen($hex) - 1;$i+= 2) $str.= chr(hexdec($hex[$i] . $hex[$i + 1])); return $str; }} < spanstyle = 'white-space:pre' > < / span > //測試Demo效果$test = new Test();$str = ’要加密的內容sxfenglei’;$data = $test->strToHex($str);echo ’加密內容:要加密的內容sxfenglei <br>’ . $data . ’<hr>’;$output = $test->hexToStr($data);echo ’解密內容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 <br>’ . $output;?>

運行結果:

加密內容:要加密的內容sxfengleiE8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569解密內容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569要加密的內容sxfenglei

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: PHP
相關文章:
国产综合久久一区二区三区