3

I need to encrypt and decrypt a string. I 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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

4 Comments

Oh, thank you. It looks easy :) Can you translate the php functions in command line functions (openssl ....) ?
@keepwalking: check out openssl rsautl. Also check out openssl rsautl -help for options like the padding-scheme.
@keepwalking: do you mean using a command line function to encrypt and decrypt a string? If so take a look at vtsm's link.
I've updated the post with the command line examples that @vtsm posted. Great link.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.