Do not store a private key on the server box however: have a SSL form available to upload it in a private admin section of the site if you are decrypting something like credit card numbers, and have it delete the key after logout, or 5-minute delay.
Anyways, handling that security is your choice, here's the class for encrypting and decrypting using a public/private keypair:
Code: Select all
<?php
/************************************
* class OpenSSLCrypt
*
* Encrypts and decrypts strings based on
* public/private RSA keypair.
*
* library written by David Balatero <david@metatank.net>
*
* EXAMPLE USAGE:
$public_key_path = "/usr/web/mycert.crt";
$private_key_path = "/usr/web/mykey.key";
$passphrase = "mypassphrase";
$Crypt = new OpenSSLCrypt($public_key_path, $private_key_path);
$Crypt->SetPassphrase($passphrase);
$string = "1234 5678 9012 3456"; // credit card number
$encrypted_string = $Crypt->Encrypt($string);
$decrypted_string = $Crypt->Decrypt($encrypted_string);
echo "Encrypted String: $encrypted_string<br>";
echo "Decrypted String: $decrypted_string";
*
* HOW-TO GENERATE KEYPAIRS
*
* їdb@logic home]$ /usr/local/ssl/bin/openssl req -x509 -newkey rsa:1025 -days 10950 -keyout mykey.key -out mycert.crt
*/
class OpenSSLCrypt {
var $public_key;
var $private_key;
var $passphrase;
function OpenSSLCrypt($public_key, $private_key) {
$this->public_key = $public_key;
$this->private_key = $private_key;
}
function SetPassphrase($phrase) {
$this->passphrase = $phrase;
}
function Encrypt($string) {
$fp = fopen($this->public_key, "r");
$public_key = fread($fp, 8192);
fclose($fp);
openssl_get_publickey($public_key);
// encrypt
openssl_public_encrypt($string, $encrypted_string, $public_key);
return $encrypted_string;
}
function Decrypt($string) {
// decrypt using privkey
$result = openssl_get_privatekey(array("file://" . $this->private_key, $this->passphrase));
openssl_private_decrypt($string, $decrypted_string, $result);
return $decrypted_string;
}
}
?>