首先說明一下對稱加密和非對稱加密的概念。
對稱加密:
采用單鑰密碼系統的加密方法,同一個密鑰可以同時用作資訊的加密和解密,這種加密方法稱為對稱加密,也稱為單密鑰加密。
非對稱加密:
非對稱加密算法需要兩個密鑰:公開密鑰(publickey:簡稱公鑰)和私有密鑰(privatekey:簡稱私鑰)。公鑰與私鑰是一對,如果用公鑰對資料進行加密,隻有用對應的私鑰才能解密。因為加密和解密使用的是兩個不同的密鑰,是以這種算法叫作非對稱加密算法。
對稱加密的特點:
- 對稱加密算法的優點是算法公開、計算量小、加密速度快、加密效率高。
- 但是對稱加密算法的缺點是在資料傳送前,發送方和接收方必須商定好秘鑰,然後使雙方都能儲存好秘鑰。
- 萬一其中一方洩露秘鑰,安全性則無法保證;
- 如果為了提高安全性引入大量秘鑰,又會使秘鑰管理會變得龐大且複雜。
非對稱加密的特點:
- 算法強度複雜,解密難度大,安全性有保障;
- 加密解密速度沒有對稱加密解密的速度快。
帶來的思考
将對稱加密和非對稱加密的優點加以整合,參考了https加解密的實作思路,我們自己封裝實作SSL(Secure Scoket Layer 安全套接層)。
具體實作思路如下:
APP端發起請求和服務端傳回資料加密:
1, 随機生成一個15位由數字字母組成的字元串作為本次請求的AES128密鑰
2,使用上述密鑰對本次請求的參數進行AES128加密,得到請求參數密文
3,使用前後端約定的RSA公鑰對1中的密鑰加密
4,把上述23的密文當參數,發起請求
參數明文
{
key : miwenKey,
data : miwenData
}
實際請求
{
data : “上述json進行base64編碼後的字元串”
}
我的示例代碼是PHP,其他語言可以參考我的實作思路:
業務代碼封裝
- 服務端傳回資料代碼:
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秘鑰參考連結
- 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非對稱加密的算法示例
生成秘鑰的代碼
// 第一步:生成私鑰,這裡我們指定私鑰的長度為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