Let me first say that I know it is a bad idea to store sensitive information in a mysql database, so please don't respond by saying "DON'T DO IT" or something to that effect. I am building a website for which it is absolutely essential to store Social Security Numbers, and I have to be able to retrieve that data back out of the DB (no hashing).
That said, I have researched the best way to encrypt/decrypt the data, and built a custom function to handle the encryption. Here is my encrypting function:
function my_data_encrypt($value){
$salt=substr(uniqid('', true), 0, 20);
$key=$salt.MY_PRIVATE_KEY;
$enc_value=base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $value, MCRYPT_MODE_CBC, md5(md5($key))));
return array("enc_value"=>$enc_value, "salt"=>$salt);
}
So basically I am generating a random string for my salt, then appending to the salt a private key MY_PRIVATE_KEY
which is defined in a separate config file. I then use mcrypt_encrypt
to encrypt the data, then base64_encode
to make the encryption safe to store in the DB. The encrypted string and the unique salt are then returned and stored in the DB together.
My thinking was that throwing a "private key" that is stored in the config file (not the DB) into the mix would add another level of security to the encryption, that way even if someone hacks the database and gets the encrypted value and the salt, they still wouldn't have everything they need to decrypt the data.
Can you security experts review my function and let me know if/how my data could be hacked and if there is anything else I could do to improve it?