首页 > django setting里面SECRET_KEY是怎么生成的

django setting里面SECRET_KEY是怎么生成的

如题,我们在django的setting里面有个
SECRET_KEY = '9b7+8l35&)ldkw%5w)bg_0f=2^+%o9floh8_v)-4k0n)4^98jl'

这个值是通过什么库来生成的


In [1]: from django.core.management import utils

In [2]: utils.get_random_secret_key()
Out[2]: '_5*c1zg+tvx(o*+6*e=@*%)7^if8f^c0r^_6ajyqz4at+%j(q='

SECRET_KEY是在startproject时候生成的,最终引用的是上述代码,具体的你可以自己去源码查看。

PS 补充一下,以上代码的django版本为1.10,具体代码执行步骤如下(其它版本也可以按照这个方法来):

1. django/core/management/commands/startproject.py
# Create a random SECRET_KEY to put it in the main settings.
options['secret_key'] = get_random_secret_key()
2. django/core/management/utils.py
def get_random_secret_key():
    """
    Return a 50 character random string usable as a SECRET_KEY setting value.
    """
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
    return get_random_string(50, chars)
3. django/utils/crypto.py
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
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))

网上找到这么一段代码

import random, string
print "".join([random.choice(string.digits + string.letters) for i in range(50)])

另一种方式

import binascii, os
print binascii.b2a_base64(os.urandom(50))

这个值是django架构自己实现生成的,通过django的源码可以看到这个值的生成方式,该值在你使用startproject开始调用生成。你可以从manage.py为入口慢慢追踪定位到目标所在。


如果要手工生成来替换,可以使用openssl rand -base64 32
32是位数,位数越大,生成的随机数就越长.

【热门文章】
【热门文章】