关键词搜索

源码搜索 ×
×

参考https加解密思路 实现自己网络请求数据传输的安全性,一致性,防篡改。(对称加密+非对称加密)

发布2021-03-01浏览9161次

详情内容

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

对称加密:
采用单钥密码系统的加密方法,同一个密钥可以同时用作信息的加密和解密,这种加密方法称为对称加密,也称为单密钥加密。

非对称加密:
非对称加密算法需要两个密钥:公开密钥(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,其他语言可以参考我的实现思路:

    业务代码封装

    1. 服务端返回数据代码:
    public function myMessage($data, $status = "success")
    {
        $aes = new AesSecurity(); //对称加密
        $rsa = new RsaService(); //非对称加密
    
        //1,随机生成一个多位由数字字母组成的字符串作为本次请求的AES128密钥 16位
        $aes_key = randomkeys(16);
        /https://cdn.jxasp.com:9143/image/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=[]);
    }
    
      11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    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);
        /https://cdn.jxasp.com:9143/image/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;
    }
    
      11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    业务层controller中获得解析后的参数

    public function create(LoginRequest $request)
    {
        //解密数据
        $data = $request->aesData($request);
    
        $name = $data['name'];
        $password = $data['password'];
    
         .
        .
        .
    }
    
      11
    • 12

    工具类:

    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;
        }
    }
    
      11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    生成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;
        }
    }
    
      11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    相关技术文章

    最新源码

    下载排行榜

    点击QQ咨询
    开通会员
    返回顶部
    ×
    微信扫码支付
    微信扫码支付
    确定支付下载
    请使用微信描二维码支付
    ×

    提示信息

    ×

    选择支付方式

    • 微信支付
    • 支付宝付款
    确定支付下载