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

Xeoncross picture Xeoncross · Jan 7, 2011 · Viewed 41.4k times · Source

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?

Answer

Eborbob picture Eborbob · Feb 9, 2016

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