Encrypting MySQL data in Drupal 6

in

The following is a Drupal 6 sample module showing how to encrypt a MySQL database column. Note that there are several cavaets:
1. This was only tested with 6.8; it might not work with other versions.
2. The sample table used only contains one row for simplicity; modifying the database code for your application is left up to you.
3. The secret key is saved in the module file; you will probably want to use a more secure method.
4. And, of course, ensuring that your MySQL installation and traffic are secure is up to you.

The module is called "destest"; change that and the code or incorporate it into your code as necessary.

If you use the module as-is as a starting point, after copying the code blocks below into the three individual files, put them into a directory called destest and then enable the module at YOURSITE/admin/build/modules.

Then, visit YOURSITE/destest and enter text into the form. That text should be saved to the database in encrypted form; you can verify that using phpMyAdmin or mysql from the command line.

destest.info
name = DES Test
description = DES Test
core = 6.x

destest.install
<?php

function destest_install() {
    drupal_install_schema('destest');
}

function destest_uninstall() {
    drupal_uninstall_schema('destest');
}

function destest_schema() {
    $schema['destest'] = array(
        'fields' => array(
            'desfield' => array(
                'description' => t('Should be encrypted.'),
                'type' => 'blob',
            ),
        ),
    );
    return $schema;
}

destest.module
<?php

define( 'DES_KEY', 'DKSF83223' );

function destest_menu() {
    $items = array();
    $items['destest'] = array(
        'title' => t('DES Test'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('destest_form'),
        'access arguments' => array('access content'),
        'description' => t('A form'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function destest_form() {
    $form = array();
    $obj = db_fetch_object( db_query(
        "SELECT DES_DECRYPT( desfield, '%s' ) AS desfield FROM {destest}", DES_KEY ) );
    $form['desfield'] = array(
        '#type' => 'textfield',
        '#title' => t('DES Field'),
        '#default_value' => $obj->desfield,
        '#size' => 20,
        '#maxlength' => 255
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save',
    );
    return $form;
}

function destest_form_submit( $form, &$form_state ) {
    db_query( "DELETE FROM {destest}" );
    db_query( "INSERT INTO {destest} ( desfield ) VALUES ( DES_ENCRYPT( %b, '%s' ) )",
                $form_state['values']['desfield'],
                DES_KEY
                );
}