php api接口加密的两种方式
0
7460
2022年10月2日
方法一:请求头加密参数
/**
* api_sk = 接口密钥 (在面板设置页面 - API 接口中获取)
* request_time = 当前请求时间的 uinx 时间戳 ( php: time() / python: time.time() )
* seqID 随机数用来避免同一秒多个请求
* 示例: $request_token = md5($request_time . ‘’ . md5($api_sk))
*/
public function _init(){
$request_time = time();
$seqID = rand(5);
$api_sk = '************';
$request_token = md5($seqID.md5($request_time .md5($api_sk)));
var_dump($request_token);
}
注意事项:
header头参数不能带下划线
可以利用redis使sign失效,例如时间戳2秒内并且每个加密只可使用一次
方法二:openssl_encrypt加密解密
1.php端
/**
* 解密
*/
public function jiemi(){
$post = $this->request->post();
$encrypted = 'C8rA65H2EOUtK+VWhvddFOatbcr/6i5/u2TP8ScVnH7qL23F975mpL45o/1I9ZYh';
$encrypted = base64_encode($encrypted);
$encrypted = base64_decode($encrypted);
$key = "1234567876666666";
$iv = "1112222211111121";
$decrypted = openssl_decrypt($encrypted, 'aes-128-cbc', $key, OPENSSL_ZERO_PADDING, $iv);
var_dump(trim($decrypted));
}
/**
* 加密
*/
public function jiami(){
$data = json_encode([
'is_artist'=>1,
'page'=>1,
'limit'=>10,
'order'=>3,
]);
if (strlen($data) % 16) {
$data = str_pad($data,strlen($data) + 16 - strlen($data) % 16, "\0");
}
$method = 'aes-128-cbc';//加密方法
$passwd = '1234567876666666';//加密方法
$iv = "1112222211111121";
$result = openssl_encrypt($data, $method, $passwd, 2,$iv);
var_dump($result);
exit;
}
2.前端
<script src="https://cdn.bootcss.com/crypto-js/3.1.9/crypto-js.min.js"></script>
<script>
/**
* 加密
* @param str
*/
var key = CryptoJS.enc.Utf8.parse('1234567876666666'); //必须16位
var iv = CryptoJS.enc.Utf8.parse('1112222211111121'); //必须16位
var encrypted = CryptoJS.AES.encrypt('{"is_artist":1,"page":1,"limit":10,"order":3}', key, { iv: iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding}).toString();
console.log(encrypted)
/**
* 解密
* @param str
*/
var str = 'C8rA65H2EOUtK+VWhvddFOatbcr/6i5/u2TP8ScVnH7qL23F975mpL45o/1I9ZYh';
var key = CryptoJS.enc.Utf8.parse('1234567876666666');// 秘钥
var iv= CryptoJS.enc.Utf8.parse('1112222211111121');//向量iv
var decrypted = CryptoJS.AES.decrypt(str,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});
console.log(decrypted.toString(CryptoJS.enc.Utf8));
</script>
执行结果打印
这个主题简介啊