Skip to content

Instantly share code, notes, and snippets.

@airtonix
Last active June 28, 2018 02:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save airtonix/6204802 to your computer and use it in GitHub Desktop.
Save airtonix/6204802 to your computer and use it in GitHub Desktop.
Django Settings. Dynamic secret key. Keep your secret key out of version control.
from hashlib import md5, sha1
from base64 import urlsafe_b64encode as b64encode
import random, string
random.seed()
pattern = "%%0%dX"
junk_len = 1024
def generate_key(max_length, seed_length, encoder=b64encode, digester=sha1):
"""
Generate a Base64-encoded 'random' key by hashing the data.
data is a tuple of seeding values. Pass arbitrary encoder and
digester for specific hashing and formatting of keys
"""
junk = ( pattern % (junk_len * 2) ) % random.getrandbits( junk_len * seed_length )
key = str(junk).encode()
return b64encode( key )[:max_length]
def random_hash():
return generate_key(96,1024,digester=sha1)
if __name__ == "__main__" :
for count in range(150) :
print random_hash()
#
# Automatically Build a Secret Key
#
# We do this so we can put base/settings/key.py into .gitignore for this project template.
# You'd obviously remove that constraint for your own projects.
try:
from .key import *
except ImportError:
from base.lib.generate_key import generate_key
secret_key_file = open(os.path.join(HERE_DIR, "key.py"), "w")
secret_key_file.write("""SECRET_KEY = "{0}" """.format(generate_key(40, 128)))
secret_key_file.close()
from .key import *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment