This guide demonstrates how to perform asymmetric encryption using the OpenSSL PHP extension. Asymmetric encryption involves the use of a pair of keys – a public key for encryption and a private key for decryption. Below are the steps to generate keys, encrypt and decrypt data.
// Generate a new key pair with a private key size of 4096 bits
$result = openssl_pkey_new([
"private_key_bits" => 4096,
]);
// Export private key to $privateKey
openssl_pkey_export($result, $privateKey);
// Get the public key
$publicKey = openssl_pkey_get_details($result)['key'];
Results:
- Private Key:
$privateKey
- Public Key:
$publicKey
// Prepare your plain data to encrypt
$plainText = "Any data";
// Encrypt and export encrypted data to $encryptedText
openssl_public_encrypt($plainText, $encryptedText, $publicKey);
Results:
- Encrypted Text:
$encryptedText
// Print the encrypted data
echo "Encrypted Text: " . base64_encode($encryptedText) . PHP_EOL;
Output:
Encrypted Text: [base64-encoded-encrypted-text]
// Decrypt the encrypted data using the private key
openssl_private_decrypt($encryptedText, $decryptedPlainText, $privateKey);
Results:
- Decrypted Text:
$decryptedPlainText
// Print the decrypted data
echo "Decrypted Text: " . $decryptedPlainText . PHP_EOL;
Output:
Decrypted Text: Any data
In this guide, we initiate a key pair, encrypt a sample plain text, print the encrypted data, decrypt it using the private key, and finally, print the decrypted data. Note that the base64_encode
function is used to ensure proper display of binary encrypted data. Ensure that you handle key management securely, especially when dealing with sensitive information.