当前位置:首页 >娱乐 >如何保证网络传输的数据安全性? 公钥与私钥是证网一对

如何保证网络传输的数据安全性? 公钥与私钥是证网一对

2024-06-29 11:32:45 [百科] 来源:避面尹邢网

如何保证网络传输的何保数据安全性?

作者:王中阳Go 安全 应用安全 非对称加密算法需要两个密钥:公开密钥(publickey:简称公钥)和私有密钥(privatekey:简称私钥)。公钥与私钥是证网一对,如果用公钥对数据进行加密,络传只有用对应的输的数据私钥才能解密。因为加密和解密使用的安全是两个不同的密钥,所以这种算法叫作非对称加密算法。何保

前言

最近在做一个新需求,证网对网络传输的络传数据安全性要求很高。

如何保障网络请求数据传输的输的数据安全性、一致性和防篡改呢?

如何保证网络传输的数据安全性? 公钥与私钥是证网一对

我们使用了对称加密与非对称加密的安全结合的策略。

如何保证网络传输的数据安全性? 公钥与私钥是证网一对

相关概念

首先说明一下对称加密和非对称加密的何保概念。

如何保证网络传输的数据安全性? 公钥与私钥是证网一对

对称加密:采用单钥密码系统的证网加密方法,同一个密钥可以同时用作信息的络传加密和解密,这种加密方法称为对称加密,输的数据也称为单密钥加密。安全

非对称加密:非对称加密算法需要两个密钥:公开密钥(publickey:简称公钥)和私有密钥(privatekey:简称私钥)。公钥与私钥是一对,如果用公钥对数据进行加密,只有用对应的私钥才能解密。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。

对称加密的特点:

  1. 对称加密算法的优点是算法公开、计算量小、加密速度快、加密效率高。
  2. 但是对称加密算法的缺点是在数据传送前,发送方和接收方必须商定好秘钥,然后使双方都能保存好秘钥。
  3. 万一其中一方泄露秘钥,安全性则无法保证;
  4. 如果为了提高安全性引入大量秘钥,又会使秘钥管理会变得庞大且复杂。

非对称加密的特点:

  1. 算法强度复杂,解密难度大,安全性有保障;
  2. 加密解密速度没有对称加密解密的速度快。

带来的思考

将对称加密和非对称加密的优点加以整合,参考了https加解密的实现思路,我们自己封装实现SSL(Secure Scoket Layer 安全套接层)。

具体实现思路如下:

APP端发起请求和服务端返回数据加密:

  1. 随机生成一个15位由数字字母组成的字符串作为本次请求的AES128密钥
  2. 使用上述密钥对本次请求的参数进行AES128加密,得到请求参数密文
  3. 使用前后端约定的RSA公钥对1中的密钥加密
  4. 把上述23的密文当参数,发起请求
参数明文{  key : miwenKey, data : miwenData}实际请求{  data : “上述json进行base64编码后的字符串”}

我的示例代码是PHP,其他语言可以参考我的实现思路:

(别问我为啥没用Go实现,甲方要求使然,哈哈哈。)

业务代码封装

  1. 服务端返回数据代码:
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=[]);}
  1. 服务端解析数据代码:
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'];     .    .    .}

工具类:

  1. 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]

  1. RSA非对称加密核心代码:
<?phpnamespace 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」,可以通过以下二维码关注。

转载本文请联系「 程序员升级打怪之旅」公众号。

责任编辑:武晓燕 来源: 程序员升职加薪之旅 网络传输数据

(责任编辑:休闲)

    推荐文章
    热点阅读