Public-Key Encryption with PHP

· Code Samples

Requires PHP Extension: php_openssl.dll or

Requires PHP Version: PHP 4 >= 4.0.6, PHP 5

Public-key encryption is a type of asymmetric cryptology where the encryption and decryption processes require different keys. There are two main components in public-key encryption: the public key and the private key.

The public key does not need to be protected. You can place it out on the public internet. The public key must be used to encrypt the data.

The private key must be protected. The private key is the only way to decrypt the data. The public key cannot be used to decrypt the data.

PHP Code Sample

// Generate a public and private key
function generate()
    // Set the key parameters
    $config = array(
        "digest_alg" => "sha512",
        "private_key_bits" => 4096,
        "private_key_type" => OPENSSL_KEYTYPE_RSA,

    // Create the private and public key
    $res = <a href="">openssl_pkey_new</a>($config);

    // Extract the private key from $res to $privKey
    <a href="">openssl_pkey_export</a>($res, $privKey);

    // Extract the public key from $res to $pubKey
    $pubKey = <a href="">openssl_pkey_get_details</a>($res);

    return array(
        'private' => $privKey,
        'public' => $pubKey["key"],
        'type' => $config,

// Encrypt data using the public key
function encrypt($data, $publicKey)
    // Encrypt the data using the public key
    <a href="">openssl_public_encrypt</a>($data, $encryptedData, $publicKey);

    // Return encrypted data
    return $encryptedData;

// Decrypt data using the private key
function decrypt($data, $privateKey)
    // Decrypt the data using the private key
    <a href="">openssl_private_decrypt</a>($data, $decryptedData, $privateKey);

    // Return decrypted data
    return $decryptedData;

// Encrypt and then decrypt a string
$arrKeys = generate();
$strEncrypted = encrypt('Hello World!', $arrKeys['public']);
$strDecrypted = decrypt($strEncrypted, $arrKeys['private']);
echo $strDecrypted;

Note: All PHP functions are hyperlinked back to the PHP Manual.

author image

About Joseph Spurrier

I'm passionate about building solutions to automate tasks and improve efficiency. Tech guy. Traveler. Runner. Guitar player. Scotch and beer enthusiast. Keybase GitHub Gists LinkedIn Twitter

Share this post

Comments powered by Disqus