Saturday, April 25, 2015

RSA Encryption with PHP

After I explained in a previous post the usage of the RSA encryption in C#, I today want to show how to do this in PHP. For this we use the library phpseclib, which provides many cryptographic functions and security protocols. First we have to download this and then upload it to the server, where our script is running. RSA is defined in the file Crypt/RSA.php, which we include via include in our script (of course the relative path has to be correct).  When creating a new instance of the class Crypt_RSA and executing the function createKey() a new key pair, consisting of public and private key, is created. The function extracts() writes this into the variables $publickey and $privatekey. The functions encrypt() and decrypt() en- and decrypt, but first the corresponding key has to be loaded via loadKey() (the public one of the receiver for encrypting, and the receiver his private one for decryption). In the following example a text is encryted and immediately decrypted again:


$rsa = new Crypt_RSA();

echo $privatekey;
echo "<br /><br />";
echo $publickey;
echo "<br /><br />";

$ciphertext = $rsa->encrypt("Secret string.");
echo $ciphertext;

echo "<br />";
echo $rsa->decrypt($ciphertext);

The script can be executed here.

No comments:

Post a Comment