Here is a class that I created to store a id/password combos for an api I integrate with. Each user can have their own unique credentials. I do not advise storing any credit card data on a non PCI compliant computer.
This is my exact class but you have some missing pieces so I have commented those. Please note that the vector is unique (Think of it as a hash) and I store that in the database along with the encrypted data.
The key is out of the public directory which goes to another topic of securing your box.
<?php
// This is on my index page but added here so you see all constants.
define('DIR', dirname(__FILE__) . '/');
class locker {
private $algorithm = MCRYPT_RIJNDAEL_256;
private $key;
private $mode = MCRYPT_MODE_CBC;
public $iv; // Public so we can change to the one used to encrypt it.
public function __construct()
{
// Lets include our key
// The key is located Outside of the public directory.
$this->key = file_get_contents(DIR .'../keys/passphrase.key');
// Create the initialization vector for added security.
$this->iv = mcrypt_create_iv(mcrypt_get_iv_size($this->algorithm, MCRYPT_MODE_ECB), MCRYPT_RAND);
}
public function encrypt($string)
{
return base64_encode(mcrypt_encrypt($this->algorithm, $this->key, base64_encode($string), $this->mode, $this->iv));
}
public function decrypt($string)
{
return base64_decode(mcrypt_decrypt($this->algorithm, $this->key, base64_decode($string), $this->mode, $this->iv));
}
// Helper functions so you can see what you can do on your own box.
public function list_modes()
{
print_r(mcrypt_list_modes());
}
public function list_algorithms()
{
print_r(mcrpt_list_algorithms());
}
}
?>
<?php
//Example usage
$locker = new locker;
$pass = $locker->encrypt('passwordvalue');
$iv = $locker->iv;
// Decrypt it
$locker = new locker;
$locker->iv = $iv;
$pass = $locker->decrypt($pass);
?>