Created
February 20, 2012 21:23
-
-
Save viccherubini/1871547 to your computer and use it in GitHub Desktop.
OpenSSL PHP example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class protector { | |
private $passphrase = null; | |
private $private_key = null; | |
private $public_key = null; | |
public function __construct() { | |
} | |
public function __destruct() { | |
} | |
public function encrypt($unencrypted_data) { | |
if (empty($this->public_key)) { | |
throw new api_exception('Please set the public key before attempting encryption.'); | |
} | |
$public_key = openssl_pkey_get_public($this->public_key); | |
if (!$public_key) { | |
throw new api_exception('Please set a valid public key before attempting encryption.'); | |
} | |
$encrypted_data = ''; | |
openssl_public_encrypt($unencrypted_data, $encrypted_data, $public_key); | |
return($encrypted_data); | |
} | |
public function decrypt($encrypted_data) { | |
if (empty($this->private_key)) { | |
throw new api_exception('Please set the private key before attempting decryption.'); | |
} | |
$private_key = openssl_pkey_get_private($this->private_key, $this->passphrase); | |
if (!$private_key) { | |
throw new api_exception('Please set a valid private key before attempting decryption.'); | |
} | |
$unencrypted_data = ''; | |
openssl_private_decrypt($encrypted_data, $unencrypted_data, $private_key); | |
return($unencrypted_data); | |
} | |
public function set_passphrase($passphrase) { | |
$this->passphrase = trim($passphrase); | |
return($this); | |
} | |
public function set_private_key($private_key) { | |
$this->private_key = trim($private_key); | |
return($this); | |
} | |
public function set_public_key($public_key) { | |
$this->public_key = trim($public_key); | |
return($this); | |
} | |
public function get_private_key() { | |
return($this->private_key); | |
} | |
public function get_public_key() { | |
return($this->public_key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice