PHP 字符串和十六进制互转
<p>今天在做项目中,因为要调用别人网站的接口,结果需要对请求和返回的时间进行十六进制加密处理,于是在网上查了下资料谢了一个转换Demo做个记录。</p><p>如果在TP下使用可以将下面函数放到common.php中</p>
<p> </p>
<p>一,加密函数</p>
<p><?php<br>/**<br> *字符串转十六进制函数<br> *@pream string $str='abc';<br> */<br> function strToHex($str){ <br> $hex="";<br> for($i=0;$i<strlen($str);$i++)<br> $hex.=dechex(ord($str[$i]));<br> $hex=strtoupper($hex);<br> return $hex;<br> } <br>?></p>
<p>二、解密函数<br><?php<br>/**<br> *十六进制转字符串函数<br> *@pream string $hex='616263';<br> */ <br> function hexToStr($hex){ <br> $str=""; <br> for($i=0;$i<strlen($hex)-1;$i+=2)<br> $str.=chr(hexdec($hex[$i].$hex[$i+1]));<br> return$str;<br> } <br>?></p>
<p>加密 解密 转换 函数使用Demo事例,这里为了方便写在了一个类中。<br><?php<br>class Test{ <br> /**<br> *字符串转十六进制函数<br> *@pream string $str='abc';<br> */<br> public function strToHex($str){ <br> $hex="";<br> for($i=0;$i<strlen($str);$i++)<br> $hex.=dechex(ord($str[$i]));<br> $hex=strtoupper($hex);<br> return $hex;<br> } <br> <br> /**<br> *十六进制转字符串函数<br> *@pream string $hex='616263';<br> */ <br> public function hexToStr($hex){ <br> $str=""; <br> for($i=0;$i<strlen($hex)-1;$i+=2)<br> $str.=chr(hexdec($hex[$i].$hex[$i+1]));<br> return$str;<br> } <br>}<br> <span style="white-space:pre"> </span>//测试Demo效果<br> $test = new Test();<br> $str = '要加密的内容sxfenglei';<br> $data = $test->strToHex($str); <br> echo '加密内容:要加密的内容sxfenglei <br>'.$data.'<hr>';<br> <br> $output = $test->hexToStr($data);<br> echo '解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 <br>'.$output;<br>?></p>
<p><br>运行结果:<br>加密内容:要加密的内容sxfenglei <br>E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569<br>解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 <br>要加密的内容sxfenglei</p>
<p> </p>
<p><br> ———————————————— <br>版权声明:本文为CSDN博主「碎碎馮同學」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。<br>原文链接:https://blog.csdn.net/fl442165035/article/details/49154891</p><br><br>
来源:https://www.cnblogs.com/wangluochong/p/11383000.html
頁:
[1]