Random ramblings about Mac, Python, TeX, programming, and more   |     |        |     |  

Beaker and PyCrypto (and web session data)

April 23, 2024  |  web, python, crypto
This post is part of a series of posts where I share my experiences developing, testing, and debugging the new implementation of my website, including this blog and my home page.

In web development, I have started to use Beaker (documentation) to handle session data (e.g., current logged in user in a session). The data for a given session can be stored in files, in a database, in memory (does not work if many processes are serving the web page), or in cookies. For small-sized data, using cookies is a suitable option (in general, a cookie should be less than 4096 bytes).

The data in a cookie should be encrypted, and Beaker supports this but does not include the actual crypto functionality. You have to install a module that provides the AES crypto functionality. Beaker supports different options, and one of them is PyCrypto. But PyCrypto is not maintained anymore and is therefor not recommended. Fortunately, several alternatives forked from, or inspired by, the original PyCrypto project exist. My experience is that PyCryptodome is a good option. You must avoid having both PyCrypto and PyCryptodome installed at the same time, as they will interfere with each other. If you are using pip to install Python modules, you can do this (skip the first line if PyCrypto is not installed):

pip3 uninstall pycrypto
pip3 install pycryptodome

If you, for some strange reasons, need to have both PyCrypto and PyCryptodome installed, you can install pycryptodomex instead of pycryptodome. However, PyCryptodome will then not be a plug-in replacement for PyCrypto (you have to import the PyCryptodome module with the name Cryptodome, and not with the name Crypto). If the goal is to use PyCryptodome with Beaker, you should ensure that PyCrypto is not installed and install pycryptodome and not pycryptodomex.

After you have installed PyCryptodome, it is straightforward to use it to encrypt the session content of cookies when using Beaker. Include the following options for sessions in Beaker (you might set other options as well; see the Beaker documentation for the details):

session_opts = {
    'session.type': 'cookie',
    'session.cookie_expires': True,
    'seesion.crypto_type': 'pycrypto',
    'session.validate_key': 'a secret key',
    'session.encrypt_key': 'another secret key'

Then, create the session middleware for your given web application app:

from beaker.middleware import SessionMiddleware
mw = SessionMiddleware(app, config = session_opts)

You should, of course, replace the keys with your own super-secret keys.

Note: PyCryptodome is not 100% compatible with with PyCrypto, but for this usage with Beaker it works well as a plug-in replacement.

Last updated: May 15, 2024