PHP 字符串和十六進制互轉


今天在做項目中,因為要調用別人網站的接口,結果需要對請求和返回的時間進行十六進制加密處理,於是在網上查了下資料謝了一個轉換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事例,這里為了方便寫在了一個類中。
<?php
class 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;
}
}
<span style="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;
?>


運行結果:
加密內容:要加密的內容sxfenglei
E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
解密內容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
要加密的內容sxfenglei

 


————————————————
版權聲明:本文為CSDN博主「碎碎馮同學」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/fl442165035/article/details/49154891


免責聲明!

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



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