Skip to content

Instantly share code, notes, and snippets.

Created August 24, 2012 17:01
Show Gist options
  • Save ndarville/3452907 to your computer and use it in GitHub Desktop.
Save ndarville/3452907 to your computer and use it in GitHub Desktop.
Generating a properly secure SECRET_KEY in Django
Two things are wrong with Django's default `SECRET_KEY` system:
1. It is not random but pseudo-random
2. It saves and displays the SECRET_KEY in ``
This snippet
1. uses `SystemRandom()` instead to generate a random key
2. saves a local `secret.txt`
The result is a random and safely hidden `SECRET_KEY`.
except NameError:
SECRET_FILE = os.path.join(PROJECT_PATH, 'secret.txt')
SECRET_KEY = open(SECRET_FILE).read().strip()
except IOError:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
secret = file(SECRET_FILE, 'w')
except IOError:
Exception('Please create a %s file with random characters \
to generate your secret key!' % SECRET_FILE)
Copy link

jrial commented Dec 27, 2016

@SEJeff: he is using that particular set of characters because that's the one used by the original function get_random_secret_key(). See line 86 on

For starters, notice how there are no capital letters in the original set. So that means you can not use string.ascii_letters, but have to use string.ascii_lowercase instead. Then take a look at the part past the integers. There are 14 "punctuation" characters there, while string.punctuation contains 32.

Your suggestion might work, or it might not. I don't know enough about cryptography nor how the SECRET_KEY is used throughout Django. But it's not a drop-in replacement since it will not generate keys containing the same set of characters.

Copy link

Actually, Django is using the exact same method to derive the secret key as this snippet and has been since at least 2012

Copy link

Properly escaped:

function django_secret() { python -c "import random,string;print(''.join([random.SystemRandom().choice(\"{}{}{}\".format(string.ascii_letters, string.digits, string.punctuation)) for i in range(63)]).replace('\\'','\\'\"\\'\"\\''))"; }
echo "DJANGO_SECRET_KEY='$(django_secret)'"

Copy link

tjps commented Jan 15, 2018

Simplest and most accurate way is to just use the function in Django directly:

python shell -c 'from import utils; print(utils.get_random_secret_key())'

Copy link

hseritt commented Mar 2, 2018

Thanks tjps ... using that in my app.

Copy link

dnintzel commented Mar 30, 2018

Is intended to be a one-time generator or would you possibly call at boot time to generate new key? I don't use heroku/(ephemeral fs), but maybe that usage would solve that issue too?

...or generating with any method including tjps' suggestion?

[update] One bad side affect to new secret key is credentials are lost and forces re-authentication (if used).

Copy link

Hi everyone, I'm very interesting to try that in our django project Epitome.

@ndarville, @SEJeff and everyone thank you for writing this code.

The reason I need this is because I am developing a script to automate installation in linux distributions. The problem is that I haven't found a way to automate the creation of a unique secret key.

I know I'm asking for a lot, but if someone could someone create a pull request to our file with a script that will automatically create a secret key regardless of being in linux or windows and with the user not having to do anything further, I will be extremely grateful. I have tried implementing the code snippets here but with no success.

Please send me a message if you would like to discuss further, I will be happy to hear from you.

Copy link

in windows python shell -c "from import utils; print(utils.get_random_secret_key())" (nb double not single quotes)

Copy link

Simplest and most accurate way is to just use the function in Django directly:

python shell -c 'from import utils; print(utils.get_random_secret_key())'

That's great. Thanks a lot for this info @tjps.

Copy link

This is one of those gists I made a million years ago for myself and then forgot all about that seems to have taken on its own SEO life subsequently. You definitely shouldn't use the original advice at this point. :)

Copy link

If using Python 3.6+ also consider e.g. secrets.token_urlsafe .

Copy link

Another form of the one line command is:

$ python -c "from import get_random_secret_key; print(get_random_secret_key())"


Please note that your local interpreter might only be available through a versioned binary name, like python3, and/or its absolute path, e.g. /usr/lib/python3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment