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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章