如何使用 python 为 nginx 中的安全链接模块创建链接?我正在寻找使用 nginx 来提供具有过期链接的安全文件。 链接到 Nginx 维基
问问题
5187 次
3 回答
5
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}")
于 2018-10-11T15:58:04.663 回答
2
接受的答案是不正确的,因为它只对密钥进行哈希处理,而不是对密钥、url 和过期时间的组合进行哈希处理。
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
}
于 2015-03-14T20:56:13.630 回答
-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)
data 是您生成的表单网址:
/securedir/file.txt?st=PIrEk4JX5gJPTGmvqJG41g&e=1324527723
于 2012-07-23T11:55:31.343 回答