Encrypt and Decrypt text with RSA in PHP
Sure!
The following example demonstrates how to encrypt and decrypt text using RSA in PHP.
Example of Encrypt and Decrypt text with RSA in PHP
<?php
// Load the key file
$privateKey = openssl_pkey_get_private('file://private.key');
$publicKey = openssl_pkey_get_public('file://public.key');
// Encrypt the data
$data = 'Hello World!';
openssl_public_encrypt($data, $encrypted, $publicKey);
// Decrypt the data
openssl_private_decrypt($encrypted, $decrypted, $privateKey);
echo $decrypted;
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
This example assumes that you have a private key file called private.key and a public key file called public.key in the same directory as your PHP script. You can generate these key files using the openssl command-line tool.
First, generate a private key and a self-signed certificate (which contains the public key):
openssl req -x509 -newkey rsa:2048 -keyout private.key -out certificate.pem -nodesNext, extract the public key from the certificate:
openssl x509 -pubkey -noout -in certificate.pem -out public.key