云塔中心作为一个核心,是需要和其他网站进行交互的,同时连接多个数据库不是一个明智之举,那样会大大减慢云塔中心的运行速度,通过API接口进行交互以及资料传递,或许是一个不错的解决方法。

那么如何去保证数据传递的安全以及资料的真实准确性,一般会使用加密。加密的方式也有很多种,例如彩虹易支付中,使用的是md5对传递的资料和商户密码进行了哈希,通过验证哈希来判断是否正确,但这种验证方法也是有方法被伪造的。所以我们使用安全性更高的RSA加密解密。

使用PHP生成RSA密钥

    public function genKeys() {
        $resource = openssl_pkey_new();
        openssl_pkey_export($resource, $this->privateKey);
        $detail = openssl_pkey_get_details($resource);
        $this->publicKey = $detail['key'];
    }

这里我们使用的是php中的openssl_pkey_new来生成我们的密钥,我们可以通过openssl_pkey_export来提取的我们的privateKey,在代码中我们储存到$this->privateKey里面。

然后我们使用openssl_pkey_get_details来获取我们的publicKey,代码中我们储存到$this->publicKey里面

使用私钥进行加密

    public function privateEncrypt(array $data) {
        $data = json_encode($data);
        $result = openssl_private_encrypt($data, $encrypted, $this->privateKey);
        if($result === false) {
            return NULL;
        } else {
            return $encrypted;
        }
    }

这里就是我们使用私钥进行加密的代码,首先我们对我们需要加密的资料进行JSON包装,之后我们通过php中的openssl_private_encrypt进行加密,加密的结果储存到$encrypted中,并且返回一个bool$result当中。

如果$resulttrue,证明加密成功,我们就可以返回加密之后的内容了

使用公钥进行解密

    public function publicDecrypt(array $data) {
        $result = openssl_public_decrypt($data, $decrypted, $this->publicKey);
        if($result === false) {
            return NULL;
        } else {
            return json_decode($decrypted, true);
        }
    }

这里就是我们使用公钥进行解密的代码,我们通过php中的openssl_public_decrypt进行解密,解密的结果储存到$decrypted中,并且返回一个bool$result当中。

如果$resulttrue,证明解密成功,我们就可以返回解密之后的内容了