If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

This doc explains how to keep information encrypted  into the database, even if  the email is the one you use for auth.

In your module folder you can create a python file: utils.py

 

from gluon.http import HTTP
import gluon.contrib.aes as AES
import base64
import os

def crypt(action, data, iv_random=True):
    try:
        # key, it has to be 128, 192, o 256 bits, check configuration
        key = 'This is a key256 XXXX XX X XXXXX'

        # Initialization vector. It has the first 16 bytes in the message.
        # it is used to have the same message encrypted but with different result
        # CBCMode de AES
        if iv_random:
            iv = os.urandom(16 * 1024)[0:16]
        else:
            # This case should be for the emails
            iv = ' ' * 16

        # The information of the message have to be multiple of 16 (AES block size), for this reason PADDING.
        # PADDING Guarantees that the message is multiple of the block
        padding = ' '
        pad = lambda s:  s + (16 - len(s) % 16) * padding

        if action == 'encrypt':
            return base64.b64encode(iv + AES.new(key, AES.MODE_CBC, iv).encrypt(pad(data)))
        elif action == 'decrypt':
            return AES.new(key, AES.MODE_CBC, data[:16]).decrypt(base64.b64decode(data).rstrip(padding))[16:]
    except Exception as e:
        HTTP(str(e))

 

In your model db.py:

from utils import crypt as CRYPT
db.auth_user.email.filter_in = lambda data: CRYPT('encrypt', data, iv_random=False)
db.auth_user.email.filter_out = lambda data: CRYPT('decrypt', data, iv_random=False)

 

In web2py book, you can find more info about filter_in and filter_out.

With the code before if you need to encrypt the email, and this is the one you use for login, use:

iv_random=False

In other cases use: iv_random=True

Here there is a good explanation about IV:

http://stackoverflow.com/questions/9049789/aes-encryption-key-versus-iv

 

 

Comments (0)


Hosting graciously provided by:
Python Anywhere