RSA数据加密解密

RSA数据加密解密
1
2
3
4
5
6
7
8
9
10
11
<?php
//定义常量
define("INVOICE_PRINT_URL", '');
define("MERCHANT_ID", '');
define("MERCHANT_SECRET", '');
define("PLATFORM_PUBLIC_KEY", '');
define("MERCHANT_PUBLIC_KEY", '');
define("MERCHANT_PRIVATE_KEY", $'');
define("ACCOUNT_VALUE", '');

const KEYSIZE = 2048;//密钥长度
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
<?php

/**
* @FuncName:getPlatformPublicKey
* @Description 获取平台公钥
* @User ZHaoGuiBin
* @Date 2020-08-17 8:29
* @return false|resource
*/
private static function getPlatformPublicKey()
{
return openssl_pkey_get_public(PLATFORM_PUBLIC_KEY);
}


/**
* @FuncName:getMerchantPrivateKey
* @Description 获取商户私钥
* @User ZHaoGuiBin
* @Date 2020-08-17 8:29
* @return false|resource
*/
private static function getMerchantPrivateKey()
{
return openssl_pkey_get_private(MERCHANT_PRIVATE_KEY);
}

/**
* @FuncName:getMerchantPublicKey
* @Description 获取商户公钥
* @User ZHaoGuiBin
* @Date 2020-08-17 8:29
* @return false|resource
*/
private static function getMerchantPublicKey()
{
return openssl_pkey_get_public(MERCHANT_PUBLIC_KEY);
}

/**
* @FuncName:sslPublicEncrypt
* @Description 公钥加密数据
* @User ZHaoGuiBin
* @Date 2020-08-14 10:42
* @param $source_data
* @return array
*/
private static function sslPublicEncrypt($source_data)
{

if (!$source_data) {
return ['code' => 500, 'message' => '加密数据为空'];
}

$data = "";
$key = self::getPlatformPublicKey();

if (!$key) {
return ['code' => 500, 'message' => '平台密钥不正确,请检查平台密钥配置'];
}

$dataArray = str_split($source_data, self::KEYSIZE / 8 - 11); //加密最长长度为(self::KEYSIZE / 8 - 11)

foreach ($dataArray as $value) {
$res = openssl_public_encrypt($value, $encryptedTemp, $key);
if (!$res) {
return ['code' => 500, 'message' => '加密失败,请重试'];
}
$data .= $encryptedTemp;
}

openssl_free_key($key);
return ['code' => 200, 'message' => base64_encode($data)];
}

/**
* @FuncName:sslPrivateDecrypt
* @Description 私钥解密
* @User ZHaoGuiBin
* @Date 2020-08-14 10:56
* @param $encryptData
* @return array
*/
private static function sslPrivateDecrypt($encryptData)
{

if (!$encryptData) {
return ['code' => 500, 'message' => '没有解密数据'];
}

$decrypted = "";
$decodeStr = base64_decode($encryptData);
$key = self::getMerchantPrivateKey();
if (!$key) {
return ['code' => 500, 'message' => '获取密钥失败,请联系管理员处理'];
}

$enArray = str_split($decodeStr, self::KEYSIZE / 8);

foreach ($enArray as $va) {
$decryptedTemp = "";
$res = openssl_private_decrypt($va, $decryptedTemp, $key, OPENSSL_PKCS1_PADDING);
if (!$res) {
return ['code' => 500, 'message' => '加密失败,请联系管理员处理'];
}
$decrypted .= $decryptedTemp;
}
openssl_free_key($key);
return ['code' => 200, 'message' => $decrypted];
}