Location: PHPKode > scripts > OpenSSLCrypt > opensslcrypt/class.OpenSSLCrypt.php
<?php
/************************************
 * class OpenSSLCrypt
 *
 * Encrypts and decrypts strings based on
 * public/private RSA keypair.
 *
 * library written by David Balatero <hide@address.com>
 *
 * EXAMPLE USAGE:
	$public_key_path = "/usr/web/mycert.crt";
	$private_key_path = "/usr/web/mykey.key";
	$passphrase = "somepassword";

	$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
 *
 * [hide@address.com 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;
	}
}
?>
Return current item: OpenSSLCrypt