2015-04-20 69 views
1

我有一個python腳本,需要在整個執行過程中多次更改django SECRET_KEY。這裏是什麼,我試圖做一個例子:在腳本中更改Django密鑰

from django.core import signing 

# SECRET_KEY = "abc" 
print signing.dumps("value") 
# SECRET_KEY = "123" 
print signing.dumps("value") 
# SECRET_KEY = "test" 
print signing.dumps("value") 

signing.dumps方法需要SECRET_KEY是已經建立的是,它似乎並不有一個參數在腳本中改變它。

我會怎樣在腳本中多次更改SECRET_KEY

回答

0

如果在dumps method in signing.py仔細觀察,你會發現它接受一個關鍵的簽名密鑰:

如果關鍵是沒有,settings.SECRET_KEY來代替。

def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False): 
    """ 
    Returns URL-safe, sha1 signed base64 compressed JSON string. If key is 
    None, settings.SECRET_KEY is used instead. 
    If compress is True (not the default) checks if compressing using zlib can 
    save some space. Prepends a '.' to signify compression. This is included 
    in the signature, to protect against zip bombs. 
    Salt can be used to namespace the hash, so that a signed string is 
    only valid for a given namespace. Leaving this at the default 
    value or re-using a salt value across different parts of your 
    application without good cause is a security risk. 
    The serializer is expected to return a bytestring. 
    """ 

因此,所有你需要做的就是繞過每次不同的密鑰:

SECRET_KEY = "abc" 
print signing.dumps("value", key=SECRET_KEY) 
SECRET_KEY = "123" 
print signing.dumps("value", key=SECRET_KEY) 

也就是說,這看起來像一個壞主意,我因爲你沒有使用默認簽名鍵。如果您確實需要簽署文本,請使用Signer class創建並實例化新對象,並使用它,如Signer(key="NEW KEY")

0

兩件事情:

  1. 你不需要改變你的SECRET_KEY。事實上,如果你這樣做,你將無法簽名你簽署的東西!
  2. signing.dumps()函數用於複雜的數據類型,例如字典和元組。

如果你有,你想申請一個值,你可以做到以下幾點:

from django.core.signing import Signer 
signer = Signer() 
value = signer.sign('My string') 

...然後形式發佈後,你可以驗證簽名.. 。

try: 
    original = signer.unsign(value) 
except signing.BadSignature: 
    print("Tampering detected!") 
+0

您還可以使用:signer = Signer('my-other-secret')來設置密鑰 – jbiz