Blame view

common/exts/RSACrypt.php 1.06 KB
d5e57a77   xu   app-api
1
2
3
4
5
6
<?php

namespace common\exts;

class RSACrypt
{
d5e57a77   xu   app-api
7
8
9
10
11
12
13
14
15
16
17
    private $pubkey;
    private $privkey;

    /**
     * RSACrypt constructor.
     * @param null $privateKey
     * @param null $publicKey
     */
    function __construct($privateKey = null, $publicKey = null)
    {
        // 获得资源类型公钥和私钥,
94d44367   xu   app-api
18
19
        $this->privkey = openssl_pkey_get_private($privateKey);
        $this->pubkey = openssl_pkey_get_public($publicKey);
d5e57a77   xu   app-api
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
    }

    /**
     * 加密
     * @param $data
     * @return string
     */
    public function encrypt($data)
    {
        if (openssl_public_encrypt($data, $encrypted, $this->pubkey)) {
            $data = base64_encode($encrypted);
            return $data;
        } else {
            return null;
        }
    }

    /**
     * 解密
     * @param $data
     * @return mixed
     */
    public function decrypt($data)
    {
        if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey)) {
            $data = $decrypted;
            return $data;
        } else {
            return null;
        }
    }
}