加密/解密字符串(PHP)

时间:2011-09-20 05:49:53

标签: php encryption

我需要加密和解密字符串。我不能使用哈希,因为解密的字符串必须是可读的。我知道mcrypt,但我正在寻找使用证书文件加密和解密的东西。

感谢。

2 个答案:

答案 0 :(得分:4)

您可以通过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);
}

要生成密钥对,简要指南为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进行了回复。

要总结该页面,一旦创建了密钥,就可以使用以下命令加密文本文件 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

答案 1 :(得分:1)

如果您想使用非对称加密,您必须使用openssl_* - 函数或phpseclib如果您的php上没有openssl。

另一方面,您无法使用对称密钥等证书。如果你有一个使用公钥加密的密文(证书包含公钥),那么你必须使用私钥解密,如果使用私钥加密密文,那么你必须使用公钥解密,否则它会赢得'工作。

相关问题