如何保證網(wǎng)絡(luò)傳輸?shù)臄?shù)據(jù)安全性?
前言
最近在做一個(gè)新需求,對(duì)網(wǎng)絡(luò)傳輸?shù)臄?shù)據(jù)安全性要求很高。
如何保障網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)傳輸?shù)陌踩?、一致性和防篡改呢?/p>
我們使用了對(duì)稱(chēng)加密與非對(duì)稱(chēng)加密的結(jié)合的策略。
相關(guān)概念
首先說(shuō)明一下對(duì)稱(chēng)加密和非對(duì)稱(chēng)加密的概念。
對(duì)稱(chēng)加密:采用單鑰密碼系統(tǒng)的加密方法,同一個(gè)密鑰可以同時(shí)用作信息的加密和解密,這種加密方法稱(chēng)為對(duì)稱(chēng)加密,也稱(chēng)為單密鑰加密。
非對(duì)稱(chēng)加密:非對(duì)稱(chēng)加密算法需要兩個(gè)密鑰:公開(kāi)密鑰(publickey:簡(jiǎn)稱(chēng)公鑰)和私有密鑰(privatekey:簡(jiǎn)稱(chēng)私鑰)。公鑰與私鑰是一對(duì),如果用公鑰對(duì)數(shù)據(jù)進(jìn)行加密,只有用對(duì)應(yīng)的私鑰才能解密。因?yàn)榧用芎徒饷苁褂玫氖莾蓚€(gè)不同的密鑰,所以這種算法叫作非對(duì)稱(chēng)加密算法。
對(duì)稱(chēng)加密的特點(diǎn):
- 對(duì)稱(chēng)加密算法的優(yōu)點(diǎn)是算法公開(kāi)、計(jì)算量小、加密速度快、加密效率高。
- 但是對(duì)稱(chēng)加密算法的缺點(diǎn)是在數(shù)據(jù)傳送前,發(fā)送方和接收方必須商定好秘鑰,然后使雙方都能保存好秘鑰。
- 萬(wàn)一其中一方泄露秘鑰,安全性則無(wú)法保證;
- 如果為了提高安全性引入大量秘鑰,又會(huì)使秘鑰管理會(huì)變得龐大且復(fù)雜。
非對(duì)稱(chēng)加密的特點(diǎn):
- 算法強(qiáng)度復(fù)雜,解密難度大,安全性有保障;
- 加密解密速度沒(méi)有對(duì)稱(chēng)加密解密的速度快。
帶來(lái)的思考
將對(duì)稱(chēng)加密和非對(duì)稱(chēng)加密的優(yōu)點(diǎn)加以整合,參考了https加解密的實(shí)現(xiàn)思路,我們自己封裝實(shí)現(xiàn)SSL(Secure Scoket Layer 安全套接層)。
具體實(shí)現(xiàn)思路如下:
APP端發(fā)起請(qǐng)求和服務(wù)端返回?cái)?shù)據(jù)加密:
- 隨機(jī)生成一個(gè)15位由數(shù)字字母組成的字符串作為本次請(qǐng)求的AES128密鑰
- 使用上述密鑰對(duì)本次請(qǐng)求的參數(shù)進(jìn)行AES128加密,得到請(qǐng)求參數(shù)密文
- 使用前后端約定的RSA公鑰對(duì)1中的密鑰加密
- 把上述23的密文當(dāng)參數(shù),發(fā)起請(qǐng)求
參數(shù)明文
{
key : miwenKey,
data : miwenData
}
實(shí)際請(qǐng)求
{
data : “上述json進(jìn)行base64編碼后的字符串”
}
我的示例代碼是PHP,其他語(yǔ)言可以參考我的實(shí)現(xiàn)思路:
(別問(wèn)我為啥沒(méi)用Go實(shí)現(xiàn),甲方要求使然,哈哈哈。)
業(yè)務(wù)代碼封裝
- 服務(wù)端返回?cái)?shù)據(jù)代碼:
public function myMessage($data, $status = "success")
{
$aes = new AesSecurity(); //對(duì)稱(chēng)加密
$rsa = new RsaService(); //非對(duì)稱(chēng)加密
//1,隨機(jī)生成一個(gè)多位由數(shù)字字母組成的字符串作為本次請(qǐng)求的AES128密鑰 16位
$aes_key = randomkeys(16);
//2. 使用上述密鑰對(duì)本次請(qǐng)求的參數(shù)進(jìn)行AES128加密,得到請(qǐng)求參數(shù)密文,得到密文miwenData
$miwenData = $aes::encrypt(json_encode($data),$aes_key);
//3. 使用前后端約定的RSA公鑰對(duì)1中的密鑰加密,得到miwenKey
$miwenKey = $rsa->publicEncrypt($aes_key);
//4. base64轉(zhuǎn)碼
$data = base64_encode(json_encode([
'key'=>$miwenKey,
'data'=>$miwenData,
]));
return Response::json($data,$this->getStatusCode(),$header=[]);
}
- 服務(wù)端解析數(shù)據(jù)代碼:
public function aesData(BaseFormRequest $request)
{
//解密數(shù)據(jù)
$data = $request->post('data','');
$data = json_decode(base64_decode($data),true);
$key = $data['key'];
$data = $data['data'];
$aes = new AesSecurity(); //對(duì)稱(chēng)加密
$rsa = new RsaService(); //非對(duì)稱(chēng)加密
//1.使用前后端約定的RSA私鑰key解密,得到miwenKey(因?yàn)榭蛻?hù)端使用公鑰加密,所以服務(wù)端使用公鑰解密)
$miwenKey = $rsa->privateDecrypt($key);
//2.使用上述miwenKey對(duì)本次請(qǐng)求的data參數(shù)進(jìn)行AES128解密,得到請(qǐng)求參數(shù)密文miwenData
$miwenData = $aes::decrypt($data,$miwenKey);
//3.將json字符串轉(zhuǎn)成數(shù)組
$data = json_decode($miwenData,true);
//todo 打開(kāi)時(shí)間戳校驗(yàn)
$time = $data['time'];
//超過(guò)30秒校驗(yàn)失敗不允許繼續(xù)操作
if ($time<time()-30){
throw new Exception('訪問(wèn)超時(shí),不允許操作');
}
return $data;
}
業(yè)務(wù)層controller中獲得解析后的參數(shù)
public function create(LoginRequest $request)
{
//解密數(shù)據(jù)
$data = $request->aesData($request);
$name = $data['name'];
$password = $data['password'];
.
.
.
}
工具類(lèi):
- AES對(duì)稱(chēng)加密
<?php
/**
* [AesSecurity aes加密,支持PHP7.1]
*/
class AesSecurity
{
/**
* [encrypt aes加密]
* @param [type] $input [要加密的數(shù)據(jù)]
* @param [type] $key [加密key]
* @return [type] [加密后的數(shù)據(jù)]
*/
public static function encrypt($input, $key)
{
$data = openssl_encrypt($input, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
$data = base64_encode($data);
return $data;
}
/**
* [decrypt aes解密]
* @param [type] $sStr [要解密的數(shù)據(jù)]
* @param [type] $sKey [加密key]
* @return [type] [解密后的數(shù)據(jù)]
*/
public static function decrypt($sStr, $sKey)
{
$decrypted = openssl_decrypt(base64_decode($sStr), 'AES-128-ECB', $sKey, OPENSSL_RAW_DATA);
return $decrypted;
}
}
生成RSA秘鑰參考鏈接[1]
- RSA非對(duì)稱(chēng)加密核心代碼:
<?php
namespace App\Services;
use Exception;
class RsaService
{
/**
* 公鑰
* @var
*/
protected $public_key;
/**
* 私鑰
* @var
*/
protected $private_key;
/**
* 公鑰文件路徑
* @var
*/
protected $public_key_path = '../keys/rsa_public_key.pub';
/**
* 采用pkcs8只是為了方便程序解析
* 私鑰文件路徑
* @var
*/
protected $private_key_path = '../keys/rsa_private_key_pkcs8.pem';
/**
* 初始化配置
* RsaService constructor.
* @param bool $type 默認(rèn)私鑰加密
*/
public function __construct($type = true)
{
// if ($type) {
$this->private_key = $this->getPrivateKey();
// } else {
$this->public_key = $this->getPublicKey();
// }
}
/**
* 配置私鑰
* openssl_pkey_get_private這個(gè)函數(shù)可用來(lái)判斷私鑰是否是可用的,可用,返回資源
* @return bool|resource
*/
private function getPrivateKey()
{
$original_private_key = file_get_contents(__DIR__ . '/../' . $this->private_key_path);
return openssl_pkey_get_private($original_private_key);
}
/**
* 配置公鑰
* openssl_pkey_get_public這個(gè)函數(shù)可用來(lái)判斷私鑰是否是可用的,可用,返回資源
* @return resource
*/
public function getPublicKey()
{
$original_public_key = file_get_contents(__DIR__ . '/../' . $this->public_key_path);
return openssl_pkey_get_public($original_public_key);
}
/**
* 私鑰加密
* @param $data
* @param bool $serialize 是為了不管你傳的是字符串還是數(shù)組,都能轉(zhuǎn)成字符串
* @return string
* @throws \Exception
*/
public function privateEncrypt($data, $serialize = true)
{
$data = substr($data,0,30);
openssl_private_encrypt(
$serialize ? serialize($data) : $data,
$encrypted, $this->private_key
);
if ($encrypted === false) {
throw new \Exception('Could not encrypt the data.');
}
return base64_encode($encrypted);
}
/**
* 私鑰解密
* @param $data
* @param bool $unserialize
* @return mixed
* @throws \Exception
*/
public function privateDecrypt($data, $unserialize = true)
{
openssl_private_decrypt(base64_decode($data),$decrypted, $this->private_key);
if ($decrypted === false) {
throw new \Exception('Could not decrypt the data.');
}
return $unserialize ? unserialize($decrypted) : $decrypted;
}
/**
* 公鑰加密
* @param $data
* @param bool $serialize 是為了不管你傳的是字符串還是數(shù)組,都能轉(zhuǎn)成字符串
* @return string
* @throws \Exception
*/
public function publicEncrypt($data, $serialize = true)
{
openssl_public_encrypt(
$serialize ? serialize($data) : $data,
$encrypted, $this->public_key
);
if ($encrypted === false) {
throw new \Exception('Could not encrypt the data.');
}
return base64_encode($encrypted);
}
/**
* 公鑰解密
* @param $data
* @param bool $unserialize
* @return mixed
* @throws \Exception
*/
public function publicDecrypt($data, $unserialize = true)
{
openssl_public_decrypt(base64_decode($data),$decrypted, $this->public_key);
if ($decrypted === false) {
throw new \Exception('Could not decrypt the data.');
}
return $unserialize ? unserialize($decrypted) : $decrypted;
}
}
RSA非對(duì)稱(chēng)加密的算法示例[2]
生成秘鑰的代碼
// 第一步:生成私鑰,這里我們指定私鑰的長(zhǎng)度為1024, 長(zhǎng)度越長(zhǎng),加解密消耗的時(shí)間越長(zhǎng)
openssl genrsa -out rsa_private_key.pem 1024
// 第二步:根據(jù)私鑰生成對(duì)應(yīng)的公鑰
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pub
// 第三步:私鑰轉(zhuǎn)化成pkcs8格式,【這一步非必須,只是程序解析起來(lái)方便】
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_private_key_pkcs8.pem
相關(guān)資料
[1]生成RSA秘鑰參考鏈接: https://www.cnblogs.com/chenhaoyu/p/10695245.html
[2]RSA非對(duì)稱(chēng)加密的算法示例: https://github.com/chenyRain/Common-Code/tree/master/RSA加密解密
本文轉(zhuǎn)載自微信公眾號(hào)「 程序員升級(jí)打怪之旅」,作者「王中陽(yáng)Go」,可以通過(guò)以下二維碼關(guān)注。
轉(zhuǎn)載本文請(qǐng)聯(lián)系「 程序員升級(jí)打怪之旅」公眾號(hào)。