如何保證網絡傳輸的數據安全性?
前言
最近在做一個新需求,對網絡傳輸的數據安全性要求很高。
如何保障網絡請求數據傳輸的安全性、一致性和防篡改呢?
我們使用了對稱加密與非對稱加密的結合的策略。
相關概念
首先說明一下對稱加密和非對稱加密的概念。
對稱加密:采用單鑰密碼系統的加密方法,同一個密鑰可以同時用作信息的加密和解密,這種加密方法稱為對稱加密,也稱為單密鑰加密。
非對稱加密:非對稱加密算法需要兩個密鑰:公開密鑰(publickey:簡稱公鑰)和私有密鑰(privatekey:簡稱私鑰)。公鑰與私鑰是一對,如果用公鑰對數據進行加密,只有用對應的私鑰才能解密。因為加密和解密使用的是兩個不同的密鑰,所以這種算法叫作非對稱加密算法。
對稱加密的特點:
- 對稱加密算法的優點是算法公開、計算量小、加密速度快、加密效率高。
- 但是對稱加密算法的缺點是在數據傳送前,發送方和接收方必須商定好秘鑰,然后使雙方都能保存好秘鑰。
- 萬一其中一方泄露秘鑰,安全性則無法保證;
- 如果為了提高安全性引入大量秘鑰,又會使秘鑰管理會變得龐大且復雜。
非對稱加密的特點:
- 算法強度復雜,解密難度大,安全性有保障;
- 加密解密速度沒有對稱加密解密的速度快。
帶來的思考
將對稱加密和非對稱加密的優點加以整合,參考了https加解密的實現思路,我們自己封裝實現SSL(Secure Scoket Layer 安全套接層)。
具體實現思路如下:
APP端發起請求和服務端返回數據加密:
- 隨機生成一個15位由數字字母組成的字符串作為本次請求的AES128密鑰
- 使用上述密鑰對本次請求的參數進行AES128加密,得到請求參數密文
- 使用前后端約定的RSA公鑰對1中的密鑰加密
- 把上述23的密文當參數,發起請求
參數明文
{
key : miwenKey,
data : miwenData
}
實際請求
{
data : “上述json進行base64編碼后的字符串”
}
我的示例代碼是PHP,其他語言可以參考我的實現思路:
(別問我為啥沒用Go實現,甲方要求使然,哈哈哈。)
業務代碼封裝
- 服務端返回數據代碼:
public function myMessage($data, $status = "success")
{
$aes = new AesSecurity(); //對稱加密
$rsa = new RsaService(); //非對稱加密
//1,隨機生成一個多位由數字字母組成的字符串作為本次請求的AES128密鑰 16位
$aes_key = randomkeys(16);
//2. 使用上述密鑰對本次請求的參數進行AES128加密,得到請求參數密文,得到密文miwenData
$miwenData = $aes::encrypt(json_encode($data),$aes_key);
//3. 使用前后端約定的RSA公鑰對1中的密鑰加密,得到miwenKey
$miwenKey = $rsa->publicEncrypt($aes_key);
//4. base64轉碼
$data = base64_encode(json_encode([
'key'=>$miwenKey,
'data'=>$miwenData,
]));
return Response::json($data,$this->getStatusCode(),$header=[]);
}
- 服務端解析數據代碼:
public function aesData(BaseFormRequest $request)
{
//解密數據
$data = $request->post('data','');
$data = json_decode(base64_decode($data),true);
$key = $data['key'];
$data = $data['data'];
$aes = new AesSecurity(); //對稱加密
$rsa = new RsaService(); //非對稱加密
//1.使用前后端約定的RSA私鑰key解密,得到miwenKey(因為客戶端使用公鑰加密,所以服務端使用公鑰解密)
$miwenKey = $rsa->privateDecrypt($key);
//2.使用上述miwenKey對本次請求的data參數進行AES128解密,得到請求參數密文miwenData
$miwenData = $aes::decrypt($data,$miwenKey);
//3.將json字符串轉成數組
$data = json_decode($miwenData,true);
//todo 打開時間戳校驗
$time = $data['time'];
//超過30秒校驗失敗不允許繼續操作
if ($time<time()-30){
throw new Exception('訪問超時,不允許操作');
}
return $data;
}
業務層controller中獲得解析后的參數
public function create(LoginRequest $request)
{
//解密數據
$data = $request->aesData($request);
$name = $data['name'];
$password = $data['password'];
.
.
.
}
工具類:
- AES對稱加密
<?php
/**
* [AesSecurity aes加密,支持PHP7.1]
*/
class AesSecurity
{
/**
* [encrypt aes加密]
* @param [type] $input [要加密的數據]
* @param [type] $key [加密key]
* @return [type] [加密后的數據]
*/
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 [要解密的數據]
* @param [type] $sKey [加密key]
* @return [type] [解密后的數據]
*/
public static function decrypt($sStr, $sKey)
{
$decrypted = openssl_decrypt(base64_decode($sStr), 'AES-128-ECB', $sKey, OPENSSL_RAW_DATA);
return $decrypted;
}
}
生成RSA秘鑰參考鏈接[1]
- RSA非對稱加密核心代碼:
<?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 默認私鑰加密
*/
public function __construct($type = true)
{
// if ($type) {
$this->private_key = $this->getPrivateKey();
// } else {
$this->public_key = $this->getPublicKey();
// }
}
/**
* 配置私鑰
* openssl_pkey_get_private這個函數可用來判斷私鑰是否是可用的,可用,返回資源
* @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這個函數可用來判斷私鑰是否是可用的,可用,返回資源
* @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 是為了不管你傳的是字符串還是數組,都能轉成字符串
* @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 是為了不管你傳的是字符串還是數組,都能轉成字符串
* @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非對稱加密的算法示例[2]
生成秘鑰的代碼
// 第一步:生成私鑰,這里我們指定私鑰的長度為1024, 長度越長,加解密消耗的時間越長
openssl genrsa -out rsa_private_key.pem 1024
// 第二步:根據私鑰生成對應的公鑰
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pub
// 第三步:私鑰轉化成pkcs8格式,【這一步非必須,只是程序解析起來方便】
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_private_key_pkcs8.pem
相關資料
[1]生成RSA秘鑰參考鏈接: https://www.cnblogs.com/chenhaoyu/p/10695245.html
[2]RSA非對稱加密的算法示例: https://github.com/chenyRain/Common-Code/tree/master/RSA加密解密
本文轉載自微信公眾號「 程序員升級打怪之旅」,作者「王中陽Go」,可以通過以下二維碼關注。
轉載本文請聯系「 程序員升級打怪之旅」公眾號。