如何在python中生成nginx安全链接

时间:2012-07-23 11:55:31

标签: python nginx

如何使用python在nginx中建立安全链接模块的链接? 我希望使用nginx来提供具有过期链接的安全文件。 Link to Nginx Wiki

3 个答案:

答案 0 :(得分:2)

接受的答案是不正确的,因为它只会隐藏秘密,而不是秘密,网址和到期时间的组合。

import base64
import hashlib
import calendar
import datetime

secret = "itsaSSEEECRET"
url = "/secure/email-from-your-mom.txt"

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
expiry = calendar.timegm(future.timetuple())

secure_link = "{key}{url}{expiry}".format(key=secret,
                                          url=url,
                                          expiry=expiry)
hash = hashlib.md5(secure_link).digest()
encoded_hash = base64.urlsafe_b64encode(hash).rstrip('=')

print url + "?st=" + encoded_hash + "&e=" + str(expiry)

nginx.conf的相应部分

location /secure {

    # set connection secure link
    secure_link $arg_st,$arg_e;
    secure_link_md5 "itsaSSEEECRET$uri$secure_link_expires";

    # bad hash
    if ($secure_link = "") {
        return 403;
    }

    # link expired
    if ($secure_link = "0") {
        return 410;
    }

    # do something useful here
}

答案 1 :(得分:2)

shadfc的答案中的代码有效。 对于 Python 3 ,需要进行一些修改:

import base64
import hashlib
import calendar
import datetime

secret = "itsaSSEEECRET"
url = "/secure/email-from-your-mom.txt"

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
expiry = calendar.timegm(future.timetuple())

secure_link = f"{secret}{url}{expiry}".encode('utf-8')

hash = hashlib.md5(secure_link).digest()
base64_hash = base64.urlsafe_b64encode(hash)
str_hash = base64_hash.decode('utf-8').rstrip('=')

print(f"{url}?st={str_hash}&e={expiry}")

答案 2 :(得分:-1)

import base64
import hashlib

future = datetime.datetime.now() + datetime.timedelta(minutes=5)
url = "/securedir/file.txt"
timestamp = str(time.mktime(future.timetuple()))
security = base64.b64encode(hashlib.md5( secret ).digest()).replace('+', '-').replace('/', '_').replace("=", "")
data = str(url) + "?st=" + str(security) + "&e=" + str(timestamp)

数据是您生成的表单网址:

/securedir/file.txt?st=PIrEk4JX5gJPTGmvqJG41g&e=1324527723