php使用openssl进行Rsa长数据加密(117)解密(128)
最近在使用rsa加密,字符串过长是总是自动截取,百度了发现是rsa对加密字符有长度的限制
写篇文章,省的以后再用时来回找
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; }