PHP使用openssl進行Rsa加密,如果要加密的明文太長則會出錯,解決方法:加密的時候117個字元加密一次,然後把所有的密文拼接成一個密文;解密的時候需要128個字元解密一下,然後拼接成資料。
加密:
<code> /<span>**</span> * 加密 * <span>@param</span><span>$originalData</span> * <span>@return</span> string|void <span>*/</span> /<span>*function</span> encrypt(<span>$originalData</span>){ <span>//</span><span>if</span> (openssl_private_encrypt(<span>$originalData</span>, <span>$encryptData</span>, <span>$this</span>->rsaPrivateKey)) { <span>if</span> (openssl_public_encrypt(<span>$originalData</span>, <span>$encryptData</span>, <span>$this</span>->rsaPublicKey)) { <span>return</span> base64_encode(<span>$encryptData</span>); } <span>else</span> { <span>return</span> false; } }<span>*/</span> function encrypt(<span>$originalData</span>){ <span>$crypto</span> = <span>''</span>; <span>foreach</span> (str_split(<span>$originalData</span>, <span>117</span>) as <span>$chunk</span>) { openssl_public_encrypt(<span>$chunk</span>, <span>$encryptData</span>, <span>$this</span>->rsaPublicKey); <span>$crypto</span> .= <span>$encryptData</span>; } <span>return</span> base64_encode(<span>$crypto</span>); }</code>
解密:
<code> /<span>**</span> * 私钥解密 * <span>@param</span><span>$encryptData</span><span>*/</span> /<span>*function</span> decrypt(<span>$encryptData</span>){ <span>//</span><span>if</span> (openssl_public_decrypt(base64_decode(<span>$encryptData</span>), <span>$decryptData</span>, <span>$this</span>->rsaPublicKey)) { <span>if</span> (openssl_private_decrypt(base64_decode(<span>$encryptData</span>), <span>$decryptData</span>, <span>$this</span>->rsaPrivateKey)) { <span>return</span><span>$decryptData</span>; } <span>else</span> { <span>return</span> false; } }<span>*/</span> function decrypt(<span>$encryptData</span>){ <span>$crypto</span> = <span>''</span>; <span>foreach</span> (str_split(base64_decode(<span>$encryptData</span>), <span>128</span>) as <span>$chunk</span>) { openssl_private_decrypt(<span>$chunk</span>, <span>$decryptData</span>, <span>$this</span>->rsaPrivateKey); <span>$crypto</span> .= <span>$decryptData</span>; } <span>return</span><span>$crypto</span>; }</code>
Author:leedaning
本文網址:http://blog.csdn.net/leedaning/article/details/51780511
以上就介紹了 php使用openssl進行Rsa長資料加密117解密128,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。