PHP字符串与十六进制互转实现及示例
近期开发过程中,因需对接第三方网站接口,涉及对请求参数及返回数据进行十六进制形式的加密处理,故查阅相关资料并编写了一个转换Demo以供记录参考。
若项目基于ThinkPHP框架,可将下述函数统一放置于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;
}
} < spanstyle = "white-space:pre" > < / span > //测试Demo效果
$test = new Test();
$str = '要加密的内容sxfenglei';
$data = $test->strToHex($str);
echo '加密内容:要加密的内容sxfenglei
' . $data . '<hr>';
$output = $test->hexToStr($data);
echo '解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
' . $output;
?>
运行结果如下:
加密内容:要加密的内容sxfenglei E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 要加密的内容sxfenglei
以上内容即为本次分享的全部知识点,希望能对各位的学习有所帮助,同时也欢迎多多支持本站。