zoukankan      html  css  js  c++  java
  • 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
    ————————————————
    原文链接:https://blog.csdn.net/fl442165035/article/details/49154891

  • 相关阅读:
    LOGO在线制作网站
    ueditor和thinkphp框架整合修改版
    WAMP允许外部访问的修改方法
    javascript复习笔记
    ajax技术整理总结(1)
    图解——表和表之间的三种关系
    搭建自己的PHP框架心得——转载
    PHP 5 MySQLi 函数总结
    phpmywind调用方法大全
    phpmywind目录结构
  • 原文地址:https://www.cnblogs.com/houdj/p/14884549.html
Copyright © 2011-2022 走看看