RSACrypt.php
1.06 KB
1
2
3
4
5
6
7
8
9
10
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
<?php
namespace common\exts;
class RSACrypt
{
private $pubkey;
private $privkey;
/**
* RSACrypt constructor.
* @param null $privateKey
* @param null $publicKey
*/
function __construct($privateKey = null, $publicKey = null)
{
// 获得资源类型公钥和私钥,
$this->privkey = openssl_pkey_get_private($privateKey);
$this->pubkey = openssl_pkey_get_public($publicKey);
}
/**
* 加密
* @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;
}
}
}