我需要加密和解密一个字符串。我不能使用散列,因为解密后的字符串必须是可读的。我知道 mcrypt,但我一直在寻找使用证书文件加密和解密的东西。
谢谢。
最佳答案
您可以通过 openssl 使用公钥/私钥,使用一次或两次就非常简单
function encryptString($clearText)
{
$keyFile=fopen("public.pem","r");
$publicKey=fread($keyFile,8192);
fclose($keyFile);
openssl_get_publickey($publicKey);
openssl_public_encrypt($clearText,$cryptText,$publicKey);
return(base64_encode($cryptText));
}
function decryptString($cryptText)
{
$keyFile=fopen("private.pem","r");
$privateKey=fread($keyFile,8192);
fclose($keyFile);
openssl_get_privatekey($privateKey);
$binText = base64_decode($cryptText);
openssl_private_decrypt($binText,$clearText,$privateKey);
return($clearText);
}
要生成 key 对,一个简短的指南是 http://en.wikibooks.org/wiki/Transwiki:Generate_a_keypair_using_OpenSSL
简而言之
openssl rsa -pubout -in private.pem -out public.pem
更新
@keepwalking 在下面询问如何从命令行执行此操作,@vstm 回复了一个很好的链接 http://www.devco.net/archives/2006/02/13/public_-_private_key_encryption_using_openssl.php .
总结该页面,创建 key 后,您可以使用以下命令加密文本文件 file.txt 并将其输出到 file.ssl。
openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl
要将 file.ssl 解密为另一个文件 decrypt.txt,您可以使用以下命令。
openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt
关于php - 加密/解密字符串 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7480681/