PHP – RSA (Public-Private Key Encryption Decryption)

Struggled really hard to find a good example to encrypt and decrypt a a string using OpenSSL. But here’s hurdling through all the complexities and providing an end to end solution to the problem:

1. Create public and private key pair in PEM format. Execute the following commands on your shell:

openssl genrsa -out private.pem 1024
openssl rsa -in private.pem -out public.pem -outform PEM -pubout

2. Use the following code snippet to encrypt and decrypt a string using OpenSSL. The snippet also uses base64_encode to encode the encrypted message. This is not required but can be useful if the encrypted text is to be stored in a Database as it is UTF compliant and there is less probability of coding errors to handle the encrypted text. The encoded can later be decoded before passing over to the decryption method.

$public_key = file_get_contents('/PATH/TO/public.pem');
$private_key = file_get_contents('/PATH/TO/private.pem');

$json_data = '{
    "card_number": "1111-1111-1111-1111",
    "csv": "222",
    "exp_month": "03",
    "exp_year": "2016"

print openssl_public_encrypt($json_data, $encrypted, $public_key)."\n";
echo "Encrypted:$encrypted\n";
$b64_enc = base64_encode($encrypted);
echo "Encoded:$b64_enc\n";
$b64_dec = base64_decode($b64_enc);
print openssl_private_decrypt($b64_dec, $decrypted, $private_key)."\n";
echo "Decrypted text : $decrypted\n";
Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s