python - django setting里面SECRET_KEY是怎么生成的
阿神
阿神 2017-04-18 09:24:25
[Python讨论组]

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

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

阿神
阿神

闭关修行中......

全部回复(4)
ringa_lee
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为入口慢慢追踪定位到目标所在。

PHPz

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号