Home > Dev > Crypto > RSA Key Pair Generation, Encryption, and Decryption

RSA Key Pair Generation, Encryption, and Decryption

This code snippet shows how to generate RSA keys, and encrypt/decrypt data with them.

function generate_rsa_keys($key_size = 2048) {
    $config = [
        "private_key_bits" => $key_size,
        "private_key_type" => OPENSSL_KEYTYPE_RSA,
    ];
    $res = openssl_pkey_new($config);
    openssl_pkey_export($res, $private_key);
    $public_key = openssl_pkey_get_details($res)["key"];
    return ['private_key' => $private_key, 'public_key' => $public_key];
}

function rsa_encrypt($plaintext, $public_key) {
    openssl_public_encrypt($plaintext, $encrypted, $public_key);
    return base64_encode($encrypted);
}

function rsa_decrypt($ciphertext, $private_key) {
    openssl_private_decrypt(base64_decode($ciphertext), $decrypted, $private_key);
    return $decrypted;
}

// Usage example
$keys = generate_rsa_keys();
$public_key = $keys['public_key'];
$private_key = $keys['private_key'];

$plaintext = 'This is a secret message';
$encrypted = rsa_encrypt($plaintext, $public_key);
$decrypted = rsa_decrypt($encrypted, $private_key);

echo "Public Key: " . $public_key . "\n";
echo "Private Key: " . $private_key . "\n";
echo "Encrypted: " . $encrypted . "\n";
echo "Decrypted: " . $decrypted . "\n";
Back