django-keygen
The django-keygen
package provides an easy and convenient way to generate
secure secret keys for use with django
driven web applications.
The SECRET_KEY
setting in Django is used to provide
cryptographic signing
and is an important part of building secure Django applications.
While it is mostly used to sign session cookies, other common uses
include generating secure URL’s, protecting form content in hidden fields,
and restricting access to private resources.
Installation
The django-keygen
package is pip installable:
$ pip install django-keygen
To integrate the package with an existing django application, add it to
the installed_apps
list in the application settings:
>>> INSTALLED_APPS = [
... 'django-keygen',
... ...
... ]
Python Usage
Key generation is available using the KeyGen
class:
>>> from django_keygen import KeyGen
>>> key_generator = KeyGen()
>>> secret_key = key_generator.gen_secret_key()
By default, keys are generated using the full range of ascii charaters and are 50 characters long. This can be overwritted using key word arguments:
>>> from string import ascii_lowercase
>>> key_generator = KeyGen(length=55, chars=ascii_lowercase)
>>> secret_key = key_generator.gen_secret_key()
To use the package in your django application, you will want to persist your
secret key to disk. In your settings.py
file, add the code snippet below.
The secret_key.txt
file wil be created automatically if it does not already
exist.
>>> from django_keygen import KeyGen
>>> key_generator = KeyGen()
>>> SECRET_KEY = key_generator.from_plaintext('secret_key.txt', create_if_not_exist=True)
Command Line Usage
The command line interface is accessible via the django management tool:
$ python manage.py keygen
Just like the Python interface, you can specify the key length and charecter set used to generate the key:
$ python manage.py keygen 50 some_character_set
You can also write a new secret key to disk.
Important
The following command will overwrite an existing key file
$ python manage.py keygen >> secret_key.txt
Security Notices
It is considered bad security practice to use short security keys generating
using few unique characters. To safeguard against this, a SecurityError
is raised when django-keygen
is asked to generate an insecure key.
>>> key_generator = KeyGen(length=5, chars='abc')
Traceback (most recent call last):
...
django_keygen.exceptions.SecurityException: Secret key length is short. Consider increasing the key length.
...
The error can be ignored by specifying force=True
, in which case a warning
is issued instead:
>>> key_generator = KeyGen(length=5, chars='abc', force=True)