参考https加解密思路 实现自己网络请求数据传输的安全性,一致性,防篡改。(对称加密+非对称加密)
来源:http://g3v.cn/5d9w5
1.首先说明一下对称加密和非对称加密的概念。
1).对称加密:
采用单钥密码系统的加密方法,同一个密钥可以同时用作信息的加密和解密,这种加密方法称为对称加密,也称为单密钥加密。
2).非对称加密:
非对称加密算法需要两个密钥:公开密钥(publickey:简称公钥)和私有密钥(privatekey:简称私钥)。公钥与私钥是一对,如果用公钥对数据进行加密,只有用对应的私钥才能解密。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。
2.对称加密的特点:
对称加密算法的优点是算法公开、计算量小、加密速度快、加密效率高。
但是对称加密算法的缺点是在数据传送前,发送方和接收方必须商定好秘钥,然后使双方都能保存好秘钥。
万一其中一方泄露秘钥,安全性则无法保证;
如果为了提高安全性引入大量秘钥,又会使秘钥管理会变得庞大且复杂。
3.非对称加密的特点:
算法强度复杂,解密难度大,安全性有保障;
加密解密速度没有对称加密解密的速度快。
4.带来的思考
将对称加密和非对称加密的优点加以整合,参考了https加解密的实现思路,我们自己封装实现SSL(Secure Scoket Layer 安全套接层)。
5.具体实现思路如下:
APP端发起请求和服务端返回数据加密:
随机生成一个15位由数字字母组成的字符串作为本次请求的AES128密钥
使用上述密钥对本次请求的参数进行AES128加密,得到请求参数密文
使用前后端约定的RSA公钥对1中的密钥加密
把上述23的密文当参数,发起请求
参数明文{key : miwenKey,data : miwenData}实际请求{data : “上述json进行base64编码后的字符串”}
6.业务代码封装
服务端返回数据代码:
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'];...}
7.工具类
AES对称加密
/*** [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非对称加密核心代码:
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;}}
8.生成秘钥的代码
// 第一步:生成私钥,这里我们指定私钥的长度为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
简单分享快乐学习,如有错误请多包涵!
PS:如果没有你的关注,那我所做的将毫无意义!欢迎分享,点赞,在看。
