InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Storing Encrypted Data in a File or Database in PHP
PHP

Storing Encrypted Data in a File or Database in PHP

InfinityCoder December 21, 2016

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
/* 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 user and use it with the saved data:

1
2
3
4
5
6
7
8
$row = $db->query('SELECT *
                   FROM noc_list
                   WHERE id = 27')->fetch();
$plaintext = mcrypt_decrypt($row['algorithm'],
                            $_POST['key'],
                            $row['data'],
                            $row['mode'],
                            $row['iv']);

The save-crypt.php script shown in Example 18-1 stores encrypted data to a file.
Example 18-1. save-crypt.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function show_form() {
   $html = array();
   $html['action'] = htmlentities($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8');
 
   print<<<FORM
<form method="POST" action="{$html['action']}">
<textarea name="data"
          rows="10" cols="40">Enter data to be encrypted here.</textarea>
<br />
Encryption Key: <input type="text" name="key" />
<br />
<input name="submit" type="submit" value="Save" />
</form>
FORM;
}
 
function save_form() {
   $algorithm     = MCRYPT_BLOWFISH;
   $mode = MCRYPT_MODE_CBC;
 
   /* Encrypt data. */
   $iv = mcrypt_create_iv(mcrypt_get_iv_size($algorithm, $mode),
                          MCRYPT_DEV_URANDOM);
   $ciphertext = mcrypt_encrypt($algorithm,
                                $_POST['key'],
                                $_POST['data'],
                                $mode,
                                $iv);
 
   /* Save encrypted data. */
   $filename = tempnam('/tmp','enc') or exit($php_errormsg);
   $file = fopen($filename, 'w') or exit($php_errormsg);
   if (FALSE === fwrite($file, $iv.$ciphertext)) {
       fclose($file);
       exit($php_errormsg);
   }
 
   fclose($file) or exit($php_errormsg);
 
   return $filename;
}
 
if (isset($_POST['submit'])) {
    $file = save_form();
    echo "Encrypted data saved to file: $file";
} else {
    show_form();
}

Example 18-2 shows the corresponding program, get-crypt.php, that accepts a filename and key and produces the decrypted data.
Example 18-2. get-crypt.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function show_form() {
   $html = array();
   $html['action'] = htmlentities($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8');
 
   print<<<FORM
<form method="POST" action="{$html['action']}">
Encrypted File: <input type="text" name="file" />
<br />
Encryption Key: <input type="text" name="key" />
<br />
<input name="submit" type="submit" value="Display" />
</form>
FORM;
}
 
function display() {
   $algorithm = MCRYPT_BLOWFISH;
   $mode = MCRYPT_MODE_CBC;
 
   $file = fopen($_POST['file'], 'r') or exit($php_errormsg);
   $iv = fread($file, mcrypt_get_iv_size($algorithm, $mode));
   $ciphertext = fread($file, filesize($_POST['file']));
   fclose($file);
 
   $plaintext = mcrypt_decrypt($algorithm, $_POST['key'], $ciphertext,
                               $mode, $iv);
   echo "<pre>$plaintext</pre>";
}
 
if (isset($_POST['submit'])) {
   display();
} else {
   show_form();
}

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 delimiter after the initialization vector (IV), because mcrypt_get_iv_size() returns exactly how many bytes the decryption program needs to read to get the whole IV.

Everything after that in the file is encrypted data. 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 files provide 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.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Using Named Parameters in PHP
You want to specify your arguments to a function by …

Using Named Parameters in PHP

Defining Object Destructors in PHP
You want to define a method that is called when …

Defining Object Destructors in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap