Encrypt and Decrypt text with RSA in PHP
Sure! Here is an example of how to encrypt and decrypt text using 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;
Watch a video course
Learn object oriented PHP
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.
For example, to generate a private key and a self-signed certificate (which contains the public key), you can use the following command:
openssl req -x509 -newkey rsa:2048 -keyout private.key -out certificate.