@@ -52,7 +52,7 @@ public static function normalPublicKey($publicKey)
5252 {
5353 $ fKey = "-----BEGIN PUBLIC KEY----- \n" ;
5454 $ len = strlen ($ publicKey );
55- for ($ i = 0 ; $ i < $ len ; ) {
55+ for ($ i = 0 ; $ i < $ len ;) {
5656 $ fKey = $ fKey . substr ($ publicKey , $ i , 64 ) . "\n" ;
5757 $ i += 64 ;
5858 }
@@ -64,7 +64,7 @@ public static function normalPrivateKey($privateKey)
6464 {
6565 $ fKey = "-----BEGIN PRIVATE KEY----- \n" ;
6666 $ len = strlen ($ privateKey );
67- for ($ i = 0 ; $ i < $ len ; ) {
67+ for ($ i = 0 ; $ i < $ len ;) {
6868 $ fKey = $ fKey . substr ($ privateKey , $ i , 64 ) . "\n" ;
6969 $ i += 64 ;
7070 }
@@ -74,27 +74,47 @@ public static function normalPrivateKey($privateKey)
7474
7575 public static function encrypt ($ data , $ privateKey )
7676 {
77- // $privateKey = RSA::normalPrivateKey($privateKey); // 格式化私钥为标准的 private key
77+ if (!$ data ) {
78+ return null ;
79+ }
80+
81+ if (!is_string ($ data )) {
82+ $ data = json_encode ($ data , JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
83+ }
84+
85+ if (str_contains ($ privateKey , "PRIVATE " ) === false ) {
86+ $ privateKey = RSA ::normalPrivateKey ($ privateKey ); // 格式化私钥为标准的 private key
87+ }
7888
7989 $ res = openssl_private_encrypt ($ data , $ encrypted , $ privateKey );
8090
81- if (!$ res ) {
91+ if (!$ res ) {
8292 return false ;
8393 }
8494
8595 return Str::stringToHex ($ encrypted );
8696 }
8797
88- public function decrypt ($ data , $ publicKey )
98+ public static function decrypt ($ data , $ publicKey )
8999 {
90- // $publicKey = RSA::normalPublicKey($publicKey); // 格式化公钥为标准的 public key
100+ if (!$ data ) {
101+ return null ;
102+ }
103+
104+ if (!is_string ($ data )) {
105+ return false ;
106+ }
107+
108+ if (str_contains ($ publicKey , "PUBLIC " ) === false ) {
109+ $ publicKey = RSA ::normalPublicKey ($ publicKey ); // 格式化公钥为标准的 public key
110+ }
91111
92112 // $openssl_pub = openssl_pkey_get_public($publicKey); // 不知道作用,未使用
93113
94114 // 验签
95115 $ resArr = openssl_public_decrypt (Str::hexToString ($ data ), $ decrypted , $ publicKey );
96116
97- if (!$ resArr ){
117+ if (!$ resArr ) {
98118 return false ;
99119 }
100120
0 commit comments