PHP 数据加密工具类
最近在写一个需要加密传输数据的小项目,顺便把用的加密方法封装成一个工具类,其实就是按字节位把ASCII码进行位运算
加密解密工具类
<?php
/**
* @date 2016-06-20
* @author sallency
* 数据传输加密工具类
*/
class DataSecurityTool
{
private $key_main = [];
private $key_sub = [];
public function __construct($key_main = "this is main key", $key_sub = "this is sub key")
{
$this->key_main = str_split($key_main);
$this->key_sub = str_split($key_sub);
}
/**
* 加密函数
* @param [type] $context [description]
* @return [type] [description]
*/
public function opEncryption($context)
{
$context_bytes = str_split($context);
$context_len = count($context_bytes);
$cur_key_len = count($this->key_main);
if (empty($context_bytes)) {
return null;
}
$context_encrypted = [];
for ($i = 0; $i < $context_len; $i ++) {
$context_encrypted[$i] = ord($context_bytes[$i] ^ $this->key_main[$i % $cur_key_len]);
}
$cur_key_len = count($this->key_sub);
for ($i = 0; $i < $context_len ; $i ++) {
$context_encrypted[$i] = $context_encrypted[$i] ^ ord($this->key_sub[$i % $cur_key_len]);
}
$data = array_map(function($v) {
return chr($v);
}, $context_encrypted);
return base64_encode(implode($data));
}
/**
* 解密函数
* @param [type] $context [description]
* @return [type] [description]
*/
public function opDecryption($context)
{
$context = base64_decode($context);
$context_bytes = str_split($context);
$context_len = count($context_bytes);
$cur_key_len = count($this->key_sub);
if (empty($context_bytes)) {
return null;
}
$context_encrypted = [];
for ($i = 0; $i < $context_len; $i ++) {
$context_encrypted[$i] = ord($context_bytes[$i] ^ $this->key_sub[$i % $cur_key_len]);
}
$cur_key_len = count($this->key_main);
for ($i = 0; $i < $context_len; $i ++) {
$context_encrypted[$i] = $context_encrypted[$i] ^ ord($this->key_main[$i % $cur_key_len]);
}
$data = array_map(function($char) {
return chr($char);
}, $context_encrypted);
return implode("", $data);
}
}
使用方法
<?php
//data for encrypt
$info = [
"access_token" => "as2009_12_34",
"name" => "我的",
"age" => 25,
"sex" => "male"
];
$json_data = json_encode($info, JSON_UNESCAPED_UNICODE);
$dataSec = new DataSecurityTool();
//encrypt
$encry_data = $dataSec->opEncryption($json_data);
echo $encry_data;
//decrypt
$decry_data = $dataSec->opDecryption($encry_data);
echo $decry_data;
?>
注意如果传输的是 json 字符串的时候编码时json默认会将中文转码为unicode编码
如果是 php 5.4 可以方便的调用 JSON_UNESCAPED_UNICODE 选项告诉 json_encode 不要只能转码
如果是 php 5.4 以下的版本可以利用 urlencode 做一些封装
解决json中文乱码
<?php
/**
* 通过 urlencode 将中文编码
* @param array $json_arr [description]
* @return [type] [description]
*/
function znJsonEncode(array $json_arr)
{
$temp = array_map(function($row) {
return urlencode($row);
}, $json_arr);
return json_encode($temp);
}
/**
* 先 urldecode
* @param [type] $json_str [description]
* @param boolean $arr [description]
* @return [type] [description]
*/
function znJsonDecode($json_str, $arr = false)
{
return json_decode(urldecode($json_str), $arr);
}
即可完成中文的传输和解码
来源:oschina
链接:https://my.oschina.net/u/252076/blog/698106