我做了一些谷歌搜索并查看了文档(https://docs.djangoproject.com/en/dev/ref/settings/#secret-key),但我正在寻找一个更深入的解释,以及为什么需要它。

例如,如果密钥被泄露/其他人知道它是什么,会发生什么?


它用于生成散列。看:

>grep -Inr SECRET_KEY *
conf/global_settings.py:255:SECRET_KEY = ''
conf/project_template/settings.py:61:SECRET_KEY = ''
contrib/auth/tokens.py:54:        hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) +
contrib/comments/forms.py:86:        info = (content_type, object_pk, timestamp, settings.SECRET_KEY)
contrib/formtools/utils.py:15:    order, pickles the result with the SECRET_KEY setting, then takes an md5
contrib/formtools/utils.py:32:    data.append(settings.SECRET_KEY)
contrib/messages/storage/cookie.py:112:        SECRET_KEY, modified to make it unique for the present purpose.
contrib/messages/storage/cookie.py:114:        key = 'django.contrib.messages' + settings.SECRET_KEY
contrib/sessions/backends/base.py:89:        pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
contrib/sessions/backends/base.py:95:        if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
contrib/sessions/backends/base.py:134:        # Use settings.SECRET_KEY as added salt.
contrib/sessions/backends/base.py:143:                       settings.SECRET_KEY)).hexdigest()
contrib/sessions/models.py:16:        pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
contrib/sessions/models.py:59:        if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
core/management/commands/startproject.py:32:        # Create a random SECRET_KEY hash, and put it in the main settings.
core/management/commands/startproject.py:37:        settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents)
middleware/csrf.py:38:                % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest()
middleware/csrf.py:41:    return md5_constructor(settings.SECRET_KEY + session_id).hexdigest()

Django的加密签名文档介绍了' SECRET_KEY '设置的用法:

这个值[SECRET_KEY设置]是保护签名数据的关键——保持这个安全是至关重要的,否则攻击者可能会使用它来生成他们自己的签名值。

(本节也参考了Django文档中' SECRET_KEY '的设置。)

任何应用程序都可以使用Django中的加密签名API对值进行加密安全签名。Django本身在各种高级特性中使用了这个特性:

签名序列化数据(例如JSON文档)。 用户会话、密码重置请求、消息等的唯一令牌。 通过为请求添加(然后期望)惟一值来防止跨站点或重放攻击。 为哈希函数生成唯一的盐。

所以,一般的答案是:Django应用程序中有很多东西需要加密签名,而' SECRET_KEY '设置是用于这些东西的密钥。它需要在所有Django实例之间具有加密的强熵(计算机很难猜测)和惟一的熵。


根据Django文档关于SECRET_KEY:

The secret key is used for: All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash(). All messages if you are using CookieStorage or FallbackStorage. All PasswordResetView tokens. Any usage of cryptographic signing, unless a different key is provided. If you rotate your secret key, all of the above will be invalidated. Secret keys are not used for passwords of users and key rotation will not affect them.