Php rsa decrypt private key

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";



Definition and Usage

The openssl_private_decrypt() function will decrypt the data with the private key.

Description

Using function openssl_private_decrypt() will decrypt the data that is ecrypted using openssl_private_encrypt().

Syntax

openssl_private_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool

Parameters

Sr.NoParameterDescription
1

data

The data to be decrypted.

2

decrypted

It will have the data that is decrypted.

3

key

The private key.

4

padding

The padding you can apply are : OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING..

Return Values

PHP openssl_private_encrypt() function returns TRUE on success or FALSE on failure.

PHP Version

This function will work from PHP Version greater than 5.0.0.

Example 1

To encrypt data using openssl_public_encrypt() and decrypt using openssl_private_decrypt():

<?php
   // Save Private Key
   $privkey = openssl_pkey_new();
   openssl_pkey_export_to_file($privkey, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');
	
   //Save Public Key
   $dn = array(
      "countryName" => "IN",
      "stateOrProvinceName" => "Karnataka",
      "localityName" => "test1",
      "organizationName" => "test2",
      "organizationalUnitName" => "test3",
      "commonName" => "www.test.com",
      "emailAddress" => ""
   );
   $cert = openssl_csr_new($dn, $privkey);
   $cert = openssl_csr_sign($cert, null, $privkey, 365);
   openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/publickey.pem');
	
	
   // To encrpt data
   $data = 'Welcome To TuorialsPoint';
   $isvalid = openssl_public_encrypt ($data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);	
   echo "Data encryption : ".$crypted;
   echo ">br/<>br/<";
	
   if ($isvalid) {	
      openssl_private_decrypt ($crypted, $decrypted , file_get_contents('C:/xampp/htdocs/modules/openssl/privatekey.pem'),OPENSSL_PKCS1_PADDING);	
      echo "Data decryption : ".$decrypted;
   }
?>

This will produce following result:

Data encryption : L�_}{�E*?��9[w��7p �\ϸI�?ݟ'��ݹ�n��!��ɿ�*��Xcw���Ւ�)��/��{��!j�L��I*Ï"9eV�9�=Y\�m�i䁦�M(�0PJ��Ԇ�9��C�`�a�ݧ�b��a��?�m�G$i��eU/[�eU����\=�zLdŌn"��:[\�UA��ԭ�ힲ2@-"d��s�=2�nˣ�h��q5U��浿��9�{ݼ��|�NE�a!

Data decryption : Welcome To TuorialsPoint

Example 2

To encrypt file contents using openssl_public_encrypt() and decrypt using openssl_private_decrypt():

<?php
   // Save Private Key
   $privkey = openssl_pkey_new();
   openssl_pkey_export_to_file($privkey, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');
	
   //Save Public Key
   $dn = array(
      "countryName" => "IN",
      "stateOrProvinceName" => "Karnataka",
      "localityName" => "test1",
      "organizationName" => "test2",
      "organizationalUnitName" => "test3",
      "commonName" => "www.test.com",
      "emailAddress" => ""
   );
   $cert = openssl_csr_new($dn, $privkey);
   $cert = openssl_csr_sign($cert, null, $privkey, 365);
   openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/publickey.pem');
	
	
   // To encrpt data
   $data = file_get_contents('C:/xampp/htdocs/modules/openssl/test.txt'); // save any data in file test.txt;
   $isvalid = openssl_public_encrypt ($data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);	
   echo "Data encryption : ".$crypted;
   echo ">br/<>br/<";
	
   if ($isvalid) {	
      openssl_private_decrypt ($crypted, $decrypted , file_get_contents('C:/xampp/htdocs/modules/openssl/privatekey.pem'),OPENSSL_PKCS1_PADDING);	
      echo "Data decryption : ".$decrypted;
   }
?>

This will produce following result:

Data encryption : �ى1�A��c�`�xi�j&�!$�z˚�i�*:�)�W��ai�ٶ����|t��u��m3S��`��B�fF�qu �r�Z����2X����l�P��7�{ ��v�3(5�RdCř6�]�X`�[�2��{��d�̣bP���YHz �*ب��ZX�R�RWG*��.��˸>�|f�#ԇ]�K����@ж�'�hp��À�7�T���mΓ�&��BeR���cu�Y��ƣ��-� 

Data decryption : This is data encryption test using openssl php module.

php_function_reference.htm

How do I decode a private RSA key?

How to Decrypt an RSA Private Key Using OpenSSL.
Open terminal..
Run the open ssl command to decrypt the file $ openssl rsa -in <encrypted_private.key> -out <decrypted_private.key> Enter pass phrase for encrypted_private.key: <enter the password> writing RSA key..

How do I decrypt RSA encryption?

To decrypt a ciphertext C using an RSA public key we simply compute the plaintext M as: M = Cd mod N. Note that both RSA encryption and RSA decryption involve a modular exponentiation and so we would be well advised to use the Repeated Squares Algorithm if we want to make these processes reasonably efficient.

How do you encrypt decrypt data using a private secret key in PHP?

Encrypted data can be decrypted via openssl_private_decrypt(). This function can be used e.g. to encrypt message which can be then read only by owner of the private key. It can be also used to store secure data in database.

How use RSA encryption in PHP?

php include('Crypt/RSA..
Generate a random AES key..
Encrypt your plaintext message with the AES key, using an AEAD encryption mode or, failing that, CBC then HMAC-SHA256..
Encrypt your AES key (step 1) with your RSA public key, using RSAES-OAEP + MGF1-SHA256..