Recipe 18.11. Storing Encrypted Data in a File or Database
You want to store encrypted data that needs to be retrieved and decrypted later by your web server.
Store the additional information required to decrypt the data (such as algorithm, cipher mode, and initialization vector) along with the encrypted information, but not the key:
<?php /* Encrypt the data. */ $algorithm = MCRYPT_BLOWFISH; $mode = MCRYPT_MODE_CBC; $iv = mcrypt_create_iv(mcrypt_get_iv_size($algorithm, $mode), MCRYPT_DEV_URANDOM); $ciphertext = mcrypt_encrypt($algorithm, $_POST['key'], $_POST['data'], $mode, $iv); /* Store the encrypted data. */ $st = $db->prepare('INSERT INTO noc_list (algorithm, mode, iv, data) VALUES (?, ?, ?, ?)'); $st->execute(array($algorithm, $mode, $iv, $ciphertext)); ?>
To decrypt the data, retrieve a key from the
<?php $row = $db->query('SELECT * FROM noc_list WHERE id = 27')->fetch(); $plaintext = mcrypt_decrypt($row->algorithm, $_POST['key'], $row['data'], $row['mode'], $row['iv']); ?>
Example 18-2 shows the corresponding program, get-crypt.php , that accepts a filename and key and produces the decrypted data.
These two programs have their encryption algorithm and mode hardcoded in them, so there's no need to store this information in the file. The file consists of the initialization vector immediately followed by the encrypted data. There's no need for a
Encrypting files using the method in this recipe offers protection if an attacker gains access to the server on which the files are stored. Without the appropriate key or tremendous amounts of computing power, the attacker won't be able to read the files. However, the security that these encrypted file provides is undercut if the data to be encrypted and the encryption keys travel between your server and your users' web browsers in the clear. Someone who can intercept or monitor network traffic can see data before it even gets encrypted. To prevent this kind of eavesdropping, use SSL.
An additional risk when your web server encrypts data as in this recipe comes from how the data is visible before it's encrypted and written to a file. Someone with root or administrator access to the server can look in the memory the web server process is using and snoop on the unencrypted data and the key. If the operating system swaps the memory image of the web server process to disk, the unencrypted data might also be accessible in this swap file. This kind of attack can be difficult to pull off but can be devastating. Once the encrypted data is in a file, it's unreadable even to an attacker with root access to the web server, but if the attacker can peek at the unencrypted data before it's in that file, the encryption offers little protection.
18.11.4. See Also
Recipe 18.13 discusses SSL and protecting data as it moves over the network; documentation on