今天在做項目中,因為要調用別人網站的接口,結果需要對請求和返回的時間進行十六進制加密處理,于是在網上查了下資料謝了一個轉換Demo做個記錄。
如果在TP下使用可以將下面函數放到common.php中
一,加密函數
1
2
3
4
5
6
7
8
9
10
11
12
|
<?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 ; } ?> |
二、解密函數
1
2
3
4
5
6
7
8
9
10
11
|
<?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事例,這里為了方便寫在了一個類中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<?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 <br>' . $data . '<hr>' ; $output = $test ->hexToStr( $data ); echo '解密內容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 <br>' . $output ; ?> |
運行結果:
加密內容:要加密的內容sxfenglei
E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
解密內容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
要加密的內容sxfenglei
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/wangluochong/p/11383000.html