0

Is it acceptable to generate my SECRET_KEY in Django

base64.base64encode(os.urandom(32))

or would using

binascii.hexlify(os.urandom(32))

be a better option?

If neither of these, what would you suggest? I'm trying to avoid Django's get_random_string since I don't think that is as secure. This is for a production environment. I could also increase the integer passed to os.urandom but I'm not sure what value is not overkill.

Panda
  • 690
  • 1
  • 6
  • 19
  • 1
    The security is in the random number. b64 and hexlify are equivalent if the attacker knows which one you are using. 32 bytes of randomness is already huge... half that would be fine... larger is not needed. Some crypto schemes truncate passwords but even the larger hexlify at 64 characters should be small enough. I'd say the choice is random. – tdelaney Jun 02 '17 at 18:06
  • 1
    Why do you think `get_random_string` is less secure? It uses `SystemRandom`, which is just a more convenient interface to `os.urandom()`. – knbk Jun 02 '17 at 23:03
  • 1
    Based off the comment here https://stackoverflow.com/a/4674143/5374468 . It seems if you use only those characters there is less randomness. – Panda Jun 03 '17 at 03:07

1 Answers1

2

The best option is to use Django's get_random_secret_key method.

# Return a 50 character random string usable as a SECRET_KEY setting value.
from django.core.management.utils import get_random_secret_key
SECRET_KEY = get_random_secret_key()

Neither of those suggestions make the SECRET_KEY any more secure. You're still just generating a random string of characters. If you're really worried about security, you can increase the length of the random string generated. get_random_secret_key is really just an alias for get_random_string that alters the character set and length of the returned string:

# generate an even longer random string usable as a SECRET_KEY setting
from django.utils.crypto import get_random_string
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = get_random_string(100, chars)
ngoue
  • 1,045
  • 1
  • 12
  • 25
  • The SECRET_KEY shouldn't be generated anytime the server restarts should it? If it did it would invalidate any current sessions correct? – Panda Jun 02 '17 at 20:17
  • No, the `SECRET_KEY` is a value set in your `settings.py` file and it remains the same until you decide to rotate it for a new one either just for good measure or because you've had a security breach. My code examples are strictly for demonstrating how to manually generate a random string of characters, not code to be run each time your server starts up. – ngoue Jun 02 '17 at 20:19
  • Increasing the character set will increase the size of the search space, just like increasing the length will... at the expense of a less pretty settings file. Doing this for example: `SECRET_KEY = get_random_string(50, string.printable)` – DylanYoung Dec 13 '17 at 15:24