标签:失败 文件路径 加解密 crypto 路径 方法 chunk decrypt str
还需要注意的是加密字符串长度问题,如果加密字符串长度太长需要进行分段加解密,如下代码:
加密:(公匙加密,私密一般用来解密)
function encrypt($originalData){ $publicKeyFilePath = ‘/www/ceshi/rsa_public_key.pem‘; extension_loaded(‘openssl‘) or die(‘php需要openssl扩展支持‘); file_exists($publicKeyFilePath) or die(‘公钥的文件路径不正确‘); $publicKey = openssl_pkey_get_public(file_get_contents($publicKeyFilePath)); $publicKey or die(‘公钥不可用‘); $crypto = ‘‘; foreach (str_split($originalData, 117) as $chunk) { $encryptData = ‘‘; if(openssl_public_encrypt($chunk, $encryptData, $publicKey)){ $crypto .= $encryptData; }else{ die(‘加密失败‘); } } return base64_encode($crypto); }
解密:
function decrypt($encryptData){ $privateKeyFilePath = ‘/www/ceshi/rsa_private_key.pem‘; extension_loaded(‘openssl‘) or die(‘php需要openssl扩展支持‘); file_exists($privateKeyFilePath) or die(‘密钥的文件路径不正确‘); $privateKey = openssl_pkey_get_private(file_get_contents($privateKeyFilePath)); $privateKey or die(‘密钥不可用‘); $decryptData = ‘‘; $crypto = ‘‘; foreach (str_split(base64_decode($encryptData), 128) as $chunk) { if(openssl_private_decrypt($chunk, $decryptData, $privateKey)){ $crypto .= $decryptData; }else{ die(‘解密失败‘); } } return $crypto; }
调用:
$aa = encrypt(‘aa‘); $bb = decrypt($aa); var_dump($bb); 输出的结果为:aa
标签:失败 文件路径 加解密 crypto 路径 方法 chunk decrypt str
原文地址:http://www.cnblogs.com/herry52/p/7544898.html