Archive

Posts Tagged ‘secret key’

[flask] generate a secret key

January 1, 2015 1 comment

Problem
To implement CSRF protection, Flask-WTF needs the application to configure an encryption key. This key is used to generate encrypted tokens that are used to verify the authenticity of requests with form data.

It looks like this:

app = Flask(__name__)
app.config['SECRET_KEY'] = '<the super secret key comes here>'

What secret key to use? How to generate this secret key?

Solution #1
In the official Quickstart the following method is suggested:

>>> import os
>>> os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'

Just take that thing and copy/paste it into your code and you’re done.

Solution #2
In Django, when you create a new project, you get a settings file that contains a freshly generated 50 characters long secret key. Why not reuse this part from Django? The relevant section was easy to locate in the source code of Django:

import random
random = random.SystemRandom()

def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits.

    Taken from the django.utils.crypto module.
    """
    return ''.join(random.choice(allowed_chars) for i in range(length))

def get_secret_key():
    """
    Create a random secret key.

    Taken from the Django project.
    """
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
    return get_random_string(50, chars)

Its usage is very simple: just call the “get_secret_key()” function and copy/paste the output into your code.

Categories: django, flask Tags: , ,