avatar

RSA加密解密类2
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
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
<?php
namespace app\common\model;

class RSA {
private $public_key;
private $private_key;
private $bits = 2048;
private $errorInf = '';

function __construct(){
extension_loaded('openssl') or die('php需要openssl扩展支持');
}

/**
* 获取错误内容
* @return null
*/
public function getErrorInfo(){
$info = $this->errorInf;
$this->errorInf = null;
return $info;
}

/**
* 创建公钥私钥对
* @param int $bits #长度默认2048
* @return array|bool
*/
public function createKey($bits = 2048){
$config = [
'private_key_bits'=>$bits,
'private_key_type' => OPENSSL_KEYTYPE_RSA
];
//生成一个新的私钥和公钥对
$data = openssl_pkey_new($config);
if(!$data){
$this->errorInf = '生成公钥私钥对出错';
return false;
}

//私钥作为PEM编码的字符串导出到$sk
openssl_pkey_export($data,$sk);
if(!$sk){
$this->errorInf = '获取私钥失败';
return false;
}

$pk = openssl_pkey_get_details($data);//
if(!$pk){
$this->errorInf = '获取公钥失败';
return false;
}

return [
'sk' => $sk,
'pk' => $pk['key']
];
}

/**
* 测试公钥/私钥是否可用
* @param $key
* @param bool $type #true:私钥 false:公钥
* @return bool
*/
public function testKeys($key, $type = false){
if($type){
$ret = openssl_pkey_get_private($key);
if($ret){
$this->private_key = $ret;
$this->bits = openssl_pkey_get_details($this->private_key)['bits'];
return true;
}
return false;
}else{
$ret = openssl_pkey_get_public($key);
if($ret){
$this->public_key = $ret;
$this->bits = openssl_pkey_get_details($this->public_key)['bits'];
return true;
}
return false;
}
}

/**
* 使用公钥进行加密
* @param $data
* @return string
*/
public function publicKeyEncode($data){
if(empty($data)){
return "";
}
$return = '';
foreach (str_split($data, $this->bits/8-11) as $value){
openssl_public_encrypt($value, $encrypt_data, $this->public_key);
$return .= $encrypt_data;
}
$return = base64_encode($return);
return $return;
}

/**
* 使用私钥进行解密 #返回false视为解密失败
* @param $data
* @return bool|string
*/
public function privateKeyDecode($data){
if(empty($data)){
return "";
}
$return = '';
$data = base64_decode($data);
foreach (str_split($data, $this->bits/8) as $value){
openssl_private_decrypt($value, $decrypt_data, $this->private_key);
if($decrypt_data == null){
return false;
}
$return .= $decrypt_data;
}
return $return;
}
}