Skip to content

Instantly share code, notes, and snippets.

@viccherubini
Created February 20, 2012 21:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save viccherubini/1871547 to your computer and use it in GitHub Desktop.
Save viccherubini/1871547 to your computer and use it in GitHub Desktop.
OpenSSL PHP example
<?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);
}
}
Copy link

ghost commented Sep 9, 2016

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment