PHP使用openssl进行Rsa加密,如果要加密的明文太长则会出错,解决方法:加密的时候117个字符加密一次,然后把所有的密文拼接成一个密文;解密的时候需要128个字符解密一下,然后拼接成数据。
加密:
/** * 加密 * @param $originalData * @return string|void */ /*function encrypt($originalData){ // if (openssl_private_encrypt($originalData, $encryptData, $this->rsaPrivateKey)) { if (openssl_public_encrypt($originalData, $encryptData, $this->rsaPublicKey)) { return base64_encode($encryptData); } else { return false; } }*/ function encrypt($originalData){ $crypto = ''; foreach (str_split($originalData, 117) as $chunk) { openssl_public_encrypt($chunk, $encryptData, $this->rsaPublicKey); $crypto .= $encryptData; } return base64_encode($crypto); }
解密:
/** * 私钥解密 * @param $encryptData */ /*function decrypt($encryptData){ // if (openssl_public_decrypt(base64_decode($encryptData), $decryptData, $this->rsaPublicKey)) { if (openssl_private_decrypt(base64_decode($encryptData), $decryptData, $this->rsaPrivateKey)) { return $decryptData; } else { return false; } }*/ function decrypt($encryptData){ $crypto = ''; foreach (str_split(base64_decode($encryptData), 128) as $chunk) { openssl_private_decrypt($chunk, $decryptData, $this->rsaPrivateKey); $crypto .= $decryptData; } return $crypto; }
学习留存!
原文地址:http://blog.csdn.net/leedaning/article/details/51780511