今天在做項(xiàng)目中,因?yàn)橐{(diào)用別人網(wǎng)站的接口,結(jié)果需要對(duì)請(qǐng)求和返回的時(shí)間進(jìn)行十六進(jìn)制加密處理,于是在網(wǎng)上查了下資料謝了一個(gè)轉(zhuǎn)換Demo做個(gè)記錄。
如果在TP下使用可以將下面函數(shù)放到common.php中
一,加密函數(shù)
1
2
3
4
5
6
7
8
9
10
11
12
|
<?php /** *字符串轉(zhuǎn)十六進(jìn)制函數(shù) *@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 ; } ?> |
二、解密函數(shù)
1
2
3
4
5
6
7
8
9
10
11
|
<?php /** *十六進(jìn)制轉(zhuǎn)字符串函數(shù) *@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 ; } ?> |
加密 解密 轉(zhuǎn)換 函數(shù)使用Demo事例,這里為了方便寫在了一個(gè)類中。
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 { /** *字符串轉(zhuǎn)十六進(jìn)制函數(shù) *@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 ; } /** *十六進(jìn)制轉(zhuǎn)字符串函數(shù) *@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 > //測(cè)試Demo效果 $test = new Test(); $str = '要加密的內(nèi)容sxfenglei' ; $data = $test ->strToHex( $str ); echo '加密內(nèi)容:要加密的內(nèi)容sxfenglei <br>' . $data . '<hr>' ; $output = $test ->hexToStr( $data ); echo '解密內(nèi)容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 <br>' . $output ; ?> |
運(yùn)行結(jié)果:
加密內(nèi)容:要加密的內(nèi)容sxfenglei
E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
解密內(nèi)容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
要加密的內(nèi)容sxfenglei
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/wangluochong/p/11383000.html