New Idea: Using Password To Encrypt User's Data
I have a new idea about encrypting user's sensitive data - like credit card info and other. First, we store the logged in password in an 1 way hash like sha1 with salt, different from how it is stored in the database. We will call this hash password hash #2. ( I made up this term ) Let's say we have a password "BlackBoots" stored on the database as hash: "6c225a179ee7a4c92d7f3afef4019f2b55a00042". Upon login we will salt/mix it with "JumpingCroc" producing password hash #2 "ba95c56465470ce40db96df485620c5e8cb2be2e". We will store this password hash #2 on session (or cookie?) for later use. like:
$password = $_POST['password']; $salt = 'JumpingCroc'; $_SESSION['password_hash2'] = sha1( $password . $salt );Obviously, this has to be done upon login
Encryption of sensitive dataWhenever new sensitive data like credit card info is added by the user, the data will be encrypted using the password hash #2 as the key/salt; Before we store it in the database. So: Let's say we have credit card number 4123 4567 8901 1234, and we have to store it securely on the database, we will use reversible encryption, using "ba95c56465470ce40db96df485620c5e8cb2be2e" as the key. Something like:
$encrypted = mcrypt_encrypt( MCRYPT_RIJNDAEL_256, hex2bin($_SESSION['password_hash2']), "4123 4567 8901 1234", MCRYPT_MODE_CBC );We used the user's password as the key encrypt his own data, so basically none among the database, the server files or anything will give clue for access to the encrypted except from the user. This obviously would only work if you store their password in a non-reversible way. like SHA1. Cause if you store the password in raw form, then you can just use that password to decrypt the data. note: I discovered while writing this post that 40 characters made by SHA1 is not valid because 256 encryption only needs 32 characters. So there should be a work around. Maybe like hex2bin on the example above.
Decryption of sensitive dataNow to decrypt it, the user must be logged in, hence, enabling the system to get password hash #2 again from the logged in password. The system will use it to unlock the encrypted data from the database. something like:
$credit_card = trim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, hex2bin($_SESSION['password_hash2']), base64_decode($db_credit_card), MCRYPT_MODE_CBC ) );Note: When the user changes password, the encryption must be renewed on all the encrypted data on the database, using the new password. If the data fails to decrypt with the key, then the data is totally useless, corrupted. In case of credit card info, they should be just deleted and let the user re-input the credit card data. In case of files, then the user lost his file; Probably would be a problem. Therefore as developer, we should know when to re-encrypt the data. (We can also store the "encryption date" so we can ask the user their password on that date, if they could remember it)