@@ -72,6 +72,57 @@ public static function normalPrivateKey($privateKey)
7272 return $ fKey ;
7373 }
7474
75+ public static function chunkEncrypt ($ data , $ publicKey , $ keySize = 2048 )
76+ {
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 ($ publicKey , "PUBLIC " ) === false ) {
86+ $ publicKey = RSA ::normalPublicKey ($ publicKey ); // 格式化公钥为标准的 public key
87+ }
88+
89+ $ plaintext = $ data ;
90+ $ chunkSize = $ keySize / 8 - 11 ;
91+
92+ $ output = "" ;
93+ while ($ plaintext ) {
94+ $ chunk = substr ($ plaintext , 0 , $ chunkSize );
95+ $ plaintext = substr ($ plaintext , $ chunkSize );
96+ openssl_public_encrypt ($ chunk , $ encrypted , $ publicKey );
97+ $ output .= $ encrypted ;
98+ }
99+
100+ return Str::stringToHex ($ output );
101+ }
102+
103+ public static function chunkDecrypt ($ data , $ privateKey , $ keySize = 2048 )
104+ {
105+ if (!$ data ) {
106+ return null ;
107+ }
108+
109+ if (str_contains ($ privateKey , "PRIVATE " ) === false ) {
110+ $ privateKey = RSA ::normalPrivateKey ($ privateKey ); // 格式化私钥为标准的 private key
111+ }
112+
113+ $ output = Str::hexToString ($ data );
114+
115+ $ plaintext = "" ;
116+ while ($ output ) {
117+ $ chunk = substr ($ output , 0 , $ keySize / 8 );
118+ $ output = substr ($ output , $ keySize / 8 );
119+ openssl_private_decrypt ($ chunk , $ decrypted , $ privateKey );
120+ $ plaintext .= $ decrypted ;
121+ }
122+
123+ return $ plaintext ;
124+ }
125+
75126 public static function encrypt ($ data , $ privateKey )
76127 {
77128 if (!$ data ) {
0 commit comments