Skip to content

Instantly share code, notes, and snippets.

@mrmuminov
Last active January 11, 2024 13:17
Show Gist options
  • Save mrmuminov/441ec87dcbf87e556a513b0056d64fbf to your computer and use it in GitHub Desktop.
Save mrmuminov/441ec87dcbf87e556a513b0056d64fbf to your computer and use it in GitHub Desktop.
Asymmetric encryption with OpenSSL PHP extension

Asymmetric Encryption with OpenSSL PHP Extension

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.

Step 1: Generate Keys

// 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

Step 2: Encrypt Data

// 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

Step 3: Print Encrypted Data

// Print the encrypted data
echo "Encrypted Text: " . base64_encode($encryptedText) . PHP_EOL;

Output:

Encrypted Text: [base64-encoded-encrypted-text]

Step 4: Decrypt Data

// Decrypt the encrypted data using the private key
openssl_private_decrypt($encryptedText, $decryptedPlainText, $privateKey);

Results:

  • Decrypted Text: $decryptedPlainText

Step 5: Print Decrypted Data

// 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment