1. 数据安全介绍;
-
加密方式:
-
MD5
-
AES:对称的加密算法(还有 DES,3DES 等)。对称加密算法的底层机制会不一样。AES 有更高的速度和资源使用率,比其它的对称算法要高。
-
RSA:非对称的加密算法,效率稍差,数据量大的时候加密时间较长,一般用于小数据加密
-
加密步骤:
-
header 当中放一些基础的参数,比如 sign(加密字符串),version(版本号),app_type,did(设备号),model(机型)
-
每次 http 请求都携带验签 sign
-
sign 唯一性保证
-
请求参数、返回数据按安全性适当加密
-
access_token
-
附:RESTful api 中 HTTP 状态码
-
200:请求成功
-
201:创建成功
-
202:更新成功
-
400:无效请求
-
401:未授权
-
403:禁止访问
-
404:请求资源不存在
-
500:内部错误
2. 授权码 sign 解析;
-
重点:
-
AES加密解密算法的使用
-
sign 算法生成
-
实例:
-
环境:PHP7 + Thinkphp5
<?php
return [
'password_pre_halt' => '_#sing_ty',
'aeskey' => 'sgg45747ss223455'
];
- AES 加密类库:新建
application/lib/common/Aes.php
<?php
namespace app\common\lib;
class Aes {
private $key = null;
public function __construct() {
$this->key = config('aes.aeskey');;
}
public function encrypt($string){
$data = openssl_encrypt($string, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
$data = base64_encode($data);
return $data;
}
public function decrypt($string){
$string = base64_decode($string);
$decrypted = openssl_decrypt($string, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
return $decrypted;
}
}
- 新建:
application/lib/common/Iauth.php
<?php
namespace app\common\lib;
use app\common\lib\Aes;
class IAuth {
public static function setSign($data = []) {
ksort($data);
$string = http_build_query($data);
$string = (new Aes())->encrypt($string);
return $string;
}
}
- 新建:application/api/controller/Common.php
<?php
namespace app\api\controller;
use app\common\lib\Aes;
use app\common\lib\Iauth;
class Common{
public function testAes(){
$data = [
'did' => '12345dg',
'version' => 1
];
$str = 'sRCvj52mZ8G+u2OdHYwmysvczmCw+RrAYWiEaXFI/5A=';
echo (new Aes())->decrypt($str);exit;
}
}
- 访问:http://192.168.2.214/tp5/public/index.php/api/common/testAes
3. sign 检验。
- 修改:
application/lib/common/Iauth.php
<?php
namespace app\common\lib;
use app\common\lib\Aes;
use think\Cache;
class IAuth {
public static function setSign($data = []) {
ksort($data);
$string = http_build_query($data);
$string = (new Aes())->encrypt($string);
return $string;
}
public static function checkSignPass($data) {
$str = (new Aes())->decrypt($data['sign']);
if(empty($str)) {
return false;
}
parse_str($str, $arr);
if(!is_array($arr) || empty($arr['did']) || $arr['did'] != $data['did']) {
return false;
}
if(!config('app_debug')) {
if ((time() - ceil($arr['time'] / 1000)) > 10) {
return false;
}
if (Cache::get($data['sign'])) {
return false;
}
}
return true;
}
}
function get13TimeStamp() {
list($t1, $t2) = explode(' ', microtime());
return $t2 . ceil($t1 * 1000);
}