PHP 字符串和十六进制互转

来源:互联网 发布:行业数据报告 编辑:程序博客网 时间:2024/06/05 06:35

今天在做项目中,因为要调用别人网站的接口,结果需要对请求和返回的时间进行十六进制加密处理,于是在网上查了下资料谢了一个转换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;} } <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



0 0
原创粉丝点击