Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt data in php using Public/Private keys?

I have a small string of some data (less than 1kb) that I would like to have user agents pass to other sites when they are sent from my site. In order for the other sites to verify that I was the one that created the string I though of two options.

  1. The server pings me back to confirm (like paypal, openid, etc..)
  2. I use public/private keys to prove I sent the message (like PGP, DKIM, etc..)

I don't want to setup HMAC because that would mean I have to use custom keys for each site which would be a pain.

Out of those two choices it seems that #2 would save on bandwidth which makes it seem like a better choice.

So how can you setup public/private key cryptography using PHP and are there any downsides?

like image 383
Xeoncross Avatar asked Jan 07 '11 19:01

Xeoncross


People also ask

How encrypt and decrypt using public and private key in PHP?

openssl_public_encrypt() encrypts data with public public_key and stores the result into encrypted_data . 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.

Can you encrypt with a public key?

The other key is distributed to anyone who wants it; this key is the public key. Anyone can encrypt a message by using your public key, but only you can read it. When you receive the message, you decrypt it by using your private key.

Can PHP be used to encrypt data?

In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt. openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data.


1 Answers

Creating a private and public key pair using the PHP Openssl functions:

// Configuration settings for the key
$config = array(
    "digest_alg" => "sha512",
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key into $private_key
openssl_pkey_export($res, $private_key);

// Extract the public key into $public_key
$public_key = openssl_pkey_get_details($res);
$public_key = $public_key["key"];

You can then encrypt and decrypt using the private and public keys like this:

// Something to encrypt
$text = 'This is the text to encrypt';

echo "This is the original text: $text\n\n";

// Encrypt using the public key
openssl_public_encrypt($text, $encrypted, $public_key);

$encrypted_hex = bin2hex($encrypted);
echo "This is the encrypted text: $encrypted_hex\n\n";

// Decrypt the data using the private key
openssl_private_decrypt($encrypted, $decrypted, $private_key);

echo "This is the decrypted text: $decrypted\n\n";
like image 181
Eborbob Avatar answered Oct 17 '22 03:10

Eborbob