Monday, January 18, 2016

Encrypt/decrypt a string with RSA public/private keys in PHP

This post shows how to:

- generate private and public RSA keys using OpenSSL.
- encrypt and decrypt a string in PHP.

Requirements

Install these on a Raspberry Pi:
Apache HTTP server
PHP

Public Key and Private Key Generation

1. Create a folder to hold the public and private keys under /var/www:

mkdir RSA

Enter the folder:

cd RSA

2. Check man pages below and type Q to quit:

- Generate a RSA private key:

man genrsa

- RSA key processing tool:

man rsa

Check for the -pubout option. A public key will be output with this option.


3. Generate a 1024-bit private key:

openssl genrsa -out private_key.pem 1024

4. Obtain a public key from the private key:

openssl rsa -in private_key.pem -pubout -out public_key.pem



Encrypt and decrypt a string in PHP

1. Go back to the /var/www directory:

cd ..

2. Edit a PHP file with this command:

sudo nano rsa.php

3. Modify the rsa.php file as:


<?php
$fopen_private = fopen("rsa/private_key.pem","r");
$private_key = fread($fopen_private,8192);
fclose($fopen_private);

$fopen_public = fopen("rsa/public_key.pem","r");
$public_key = fread($fopen_public,8192);
fclose($fopen_public);

$pkey_private = openssl_pkey_get_private($private_key);
$pkey_public = openssl_pkey_get_public($public_key);

$data = "<P>My information";
$encrypted = "";
$decrypted = "";

//Encrypt with private key
openssl_private_encrypt($data, $encrypted, $pkey_private);
$encrypted = base64_encode($encrypted);

//Decrypt with public key
openssl_public_decrypt(base64_decode($encrypted), $decrypted, $pkey_public);
print $decrypted;

$encrypted = "";
$decrypted = "";

//Encrypt with public key
openssl_public_encrypt($data, $encrypted, $pkey_public);
$encrypted = base64_encode($encrypted);

//Decrypt with private key
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $pkey_private);
print $decrypted;


?>

4. Open the php file from a browser of a remote computer.




References:
Encrypt/decrypt a string with RSA public/private PEM files using Python
Encrypt/decrypt a string with code-generated RSA public/private keys in Python
php rsa加密解密實例
php rsa加密解密实例
OPENSSL入門

iOS:
Encrypt/decrypt a string with RSA public/private keys in Swift

2 comments:

  1. Hi ... Great example ...Very Useful ... Thanks !!!

    1. What is the maximum number of chars ( length of string ) that we can encrypt with this ?
    2. Anyway you can update this using openssl genpkey ?

    ReplyDelete