How to Implement RSA Encryption and Decryption in PHP with OpenSSL

This guide explains how to generate RSA key pairs on Linux, use OpenSSL commands, and implement PHP code for public‑key encryption, private‑key decryption, padding options, data‑size limits, and helper functions for handling messages larger than the RSA block size.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
How to Implement RSA Encryption and Decryption in PHP with OpenSSL

Generating RSA Key Pair

On a Linux system with OpenSSL installed, create a 1024‑bit RSA private key and derive the matching public key:

openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

PHP RSA Encryption/Decryption Example

Load the generated key files, encode the data as JSON, encrypt with the public key, base64‑encode the ciphertext for transmission, then decrypt with the private key and decode the JSON back to an array.

<?php
ini_set('error_reporting', -1);
ini_set('display_errors', -1);
header('Content-Type: text/html; charset=utf-8');

$private_key = file_get_contents('/home/users/xx/test/rsa_private_key.pem');
$public_key  = file_get_contents('/home/users/xx/test/rsa_public_key.pem');

$pi_key = openssl_pkey_get_private($private_key);
$pu_key = openssl_pkey_get_public($public_key);

$data = [
    'id'     => '1234567890',
    'name'   => '小明',
    'mobile' => '123456'
];
$json = json_encode($data);

openssl_public_encrypt($json, $encrypted, $pu_key);
$encoded = base64_encode($encrypted);

echo $encoded;

openssl_private_decrypt(base64_decode($encoded), $decrypted, $pi_key);
print_r(json_decode($decrypted, true));
?>

OpenSSL Functions Used

openssl_public_encrypt

– encrypt with a public key. openssl_private_decrypt – decrypt with a private key. openssl_private_encrypt – encrypt with a private key (digital signature). openssl_public_decrypt – decrypt with a public key.

Padding Options

The padding mode determines how many plaintext bytes can be encrypted. Common constants are:

OPENSSL_PKCS1_PADDING
OPENSSL_SSLV23_PADDING
OPENSSL_PKCS1_OAEP_PADDING
OPENSSL_NO_PADDING

Data Size Limits for a 1024‑bit Key

A 1024‑bit RSA key yields a ciphertext size of 128 bytes (1024/8). With OPENSSL_PKCS1_PADDING 11 bytes are reserved for padding, leaving a maximum plaintext length of 117 bytes. After base64_encode the 128‑byte ciphertext becomes a fixed 172‑character string.

Encrypting Data Larger Than One RSA Block

When the plaintext exceeds 117 bytes, split it into chunks smaller than that limit, encrypt each chunk, and concatenate the base64‑encoded results. Decryption reverses the process by splitting the concatenated string into 172‑character blocks.

function encrypt_rsa(string $data, $publicKey): string|false {
    // Use a safe margin below the 117‑byte limit
    $chunks = str_split($data, 100);
    $out = '';
    foreach ($chunks as $part) {
        $ok = openssl_public_encrypt($part, $enc, $publicKey);
        if (!$ok) {
            return false;
        }
        $out .= base64_encode($enc);
    }
    return $out;
}

function decrypt_rsa(string $data, $privateKey): string|false {
    // Each base64‑encoded block is exactly 172 characters
    $chunks = str_split($data, 172);
    $out = '';
    foreach ($chunks as $part) {
        $ok = openssl_private_decrypt(base64_decode($part), $dec, $privateKey);
        if (!$ok) {
            return false;
        }
        $out .= $dec;
    }
    return $out;
}

These helper functions enable secure transmission of arbitrarily long JSON payloads using RSA with OpenSSL in PHP.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

RSAencryptionOpenSSLcryptographydecryption
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.