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.
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?
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.
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.
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With