开发者

Crypt/decrypt string (PHP)

I need to encrypt and decrypt a string. 开发者_如何学PythonI can't use the hash because the decrypted string must be readable. I know about mcrypt but i was looking something that uses a certificate file to encrypt and decrypt.

Thanks.


You can use a public/private key through openssl and is pretty simple once you use it once or twice

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);
}

To generate a keypair, a brief guide is http://en.wikibooks.org/wiki/Transwiki:Generate_a_keypair_using_OpenSSL

In short

openssl rsa -pubout -in private.pem -out public.pem

Update

@keepwalking asked below how to do this from the command line and @vstm responded with a great link http://www.devco.net/archives/2006/02/13/public_-_private_key_encryption_using_openssl.php.

To summarize that page, once you have keys created, you can encrypt a text file file.txt and output it to file.ssl by using the following command.

openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl

To decrypt file.ssl to another file decrypt.txt, you can use the following command.

openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt


Well if you want to use asymmetric cryptography you either have to use the openssl_*-functions or the phpseclib if openssl is not available on your php.

The other thing is that you can't use a certificate like a symmetric key. If you have a ciphertext encrypted with a public key (a certificate contains the public key) then you have to decrypt using the private key and if the ciphertext is encrypted with the private key then you have to decrypt using the public key otherwise it won't work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜