Generate RSA Keys and Use PHP for Encryption & Decryption
This guide explains what RSA encryption is, outlines common use cases, shows step‑by‑step commands to generate private and public keys with OpenSSL, and provides a complete PHP class with methods for public‑key encryption, private‑key decryption, signing and verification, plus practical code examples.
RSA Overview
RSA is a public‑key cryptographic algorithm that is widely deployed for secure data exchange, digital signatures, and authentication. It operates on a pair of mathematically linked keys: a private key kept secret and a public key distributed to peers.
Typical Use Cases
Building API interfaces for mobile applications (iOS, Android)
Secure communications such as payment processing and identity verification
Exchanging sensitive data with third‑party or partner systems
Key Generation with OpenSSL
Generate a raw RSA private key (1024‑bit) openssl genrsa -out private_key.pem 1024 Convert the private key to PKCS#8 format (unencrypted)
openssl pkcs8 -topk8 -inform PEM -in private_key.pem -outform PEM -nocrypt -out rsa_private_key.pemExtract the public key from the PKCS#8 private key
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pemResulting files
private_key.pem # original PEM private key (1024‑bit)
rsa_private_key.pem # PKCS#8 formatted private key
rsa_public_key.pem # corresponding public keyPHP RSA Utility Class
The Rsa class encapsulates RSA operations using PHP’s OpenSSL extension. It can load keys from strings or from file paths supplied to the constructor.
namespace app\common\library;
class Rsa {
private $_config = [
'public_key' => '-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----',
'private_key' => '-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----',
];
public function __construct($private_key_filepath = null, $public_key_filepath = null) {
if (!empty($private_key_filepath) && !empty($public_key_filepath)) {
$this->_config['private_key'] = $this->_getContents($private_key_filepath);
$this->_config['public_key'] = $this->_getContents($public_key_filepath);
}
}
private function _getContents($file_path) {
file_exists($file_path) or die('Key file path error');
return file_get_contents($file_path);
}
private function _getPrivateKey() {
return openssl_pkey_get_private($this->_config['private_key']);
}
private function _getPublicKey() {
return openssl_pkey_get_public($this->_config['public_key']);
}
// ----- Encryption / Decryption -----
public function privateEncrypt($data = '', $padding = OPENSSL_PKCS1_PADDING) {
if (!is_string($data)) return null;
$encrypted = '';
foreach (str_split($data, 117) as $chunk) {
$partial = '';
if (!openssl_private_encrypt($chunk, $partial, $this->_getPrivateKey(), $padding)) return null;
$encrypted .= $partial;
}
return base64_encode($encrypted);
}
public function publicEncrypt($data = '', $padding = OPENSSL_PKCS1_PADDING) {
if (!is_string($data)) return null;
$encrypted = '';
foreach (str_split($data, 117) as $chunk) {
$partial = '';
if (!openssl_public_encrypt($chunk, $partial, $this->_getPublicKey(), $padding)) return null;
$encrypted .= $partial;
}
return base64_encode($encrypted);
}
public function privateDecrypt($encrypted = '') {
if (!is_string($encrypted)) return null;
$decrypted = '';
foreach (str_split(base64_decode($encrypted), 128) as $chunk) {
$partial = '';
if (!openssl_private_decrypt($chunk, $partial, $this->_getPrivateKey())) return null;
$decrypted .= $partial;
}
return $decrypted;
}
public function publicDecrypt($encrypted = '') {
if (!is_string($encrypted)) return null;
$decrypted = '';
foreach (str_split(base64_decode($encrypted), 128) as $chunk) {
$partial = '';
if (!openssl_public_decrypt($chunk, $partial, $this->_getPublicKey())) return null;
$decrypted .= $partial;
}
return $decrypted;
}
// ----- Signing / Verification -----
public function privateSign($data, $signature, $signature_alg = OPENSSL_ALGO_SHA1) {
$result = openssl_sign($data, $sig, $this->_getPrivateKey(), $signature_alg);
openssl_free_key($this->_getPrivateKey());
return $result === 1;
}
public function publicSign($data, $signature, $signature_alg = OPENSSL_ALGO_SHA1) {
$result = openssl_verify($data, base64_decode($signature), $this->_getPublicKey(), $signature_alg);
openssl_free_key($this->_getPublicKey());
return $result === 1;
}
}Key points:
Encryption uses a chunk size of 117 bytes (RSA‑1024 with PKCS#1 padding) because the padding consumes 11 bytes.
Decryption processes 128‑byte blocks, which is the RSA modulus size.
All encrypted/decrypted data is base64‑encoded for safe transport.
Signing and verification default to SHA‑1; the algorithm can be changed via the $signature_alg parameter.
Example Usage
$rsa = new Rsa();
$plain = 'Public key encrypt, private key decrypt';
$enc = $rsa->publicEncrypt($plain);
echo "Encrypted: $enc
";
$dec = $rsa->privateDecrypt($enc);
echo "Decrypted: $dec
";The output demonstrates that data encrypted with the public key can be recovered with the private key, and the reverse works when using the corresponding methods.
Reference
Original repository (source code and further documentation): https://github.com/Tinywan
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
