This repository has been archived by the owner on May 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
rsa_agent.php
90 lines (82 loc) · 2.22 KB
/
rsa_agent.php
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
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
<?php
class RSA
{
private static $PUBLIC_KEY = <<<EOF
-----BEGIN PUBLIC KEY-----
xxx
-----END PUBLIC KEY-----
EOF;
private static $PRIVATE_KEY = <<<EOF
-----BEGIN RSA PRIVATE KEY-----
xxx
-----END RSA PRIVATE KEY-----
EOF;
private static function getPrivateKey()
{
return openssl_pkey_get_private(self::$PRIVATE_KEY);
}
private static function getPublicKey()
{
return openssl_pkey_get_public(self::$PUBLIC_KEY);
}
public static function privateEncrypt($data = '')
{
if (!is_string($data)) {
return null;
}
$res = '';
foreach (str_split($data, 117) as $chunk) {
openssl_private_encrypt($chunk, $encryptData, self::getPrivateKey());
$res .= $encryptData;
}
return $res ? base64_encode($res) : null;
}
public static function publicEncrypt($data = '')
{
if (!is_string($data)) {
return null;
}
$res = '';
foreach (str_split($data, 117) as $chunk) {
openssl_public_encrypt($chunk, $encryptData, self::getPublicKey());
$res .= $encryptData;
}
return $res ? base64_encode($res) : null;
}
public static function privateDecrypt($data = '')
{
if (!is_string($data)) {
return null;
}
$res = '';
foreach (str_split(base64_decode($data), 128) as $chunk) {
openssl_private_decrypt($chunk, $decryptData, self::getPrivateKey());
$res .= $decryptData;
}
return $res ? $res : null;
}
public static function publicDecrypt($data = '')
{
if (!is_string($data)) {
return null;
}
$res = '';
foreach (str_split(base64_decode($data), 128) as $chunk) {
openssl_public_decrypt($chunk, $decryptData, self::getPublicKey());
$res .= $decryptData;
}
return $res;
}
}
$test = new RSA();
$encrypt = isset($_GET['encrypt']);
$data = file_get_contents("php://input");
if ($encrypt == 1) {
$ret = $test->privateEncrypt($data);
} else {
$ret = $test->privateDecrypt($data);
if (!$ret) {
$ret = $test->publicDecrypt($data);
}
}
print_r($ret);