如何使的链接,使用python在nginx的安全链接模块? 我期待使用nginx的服务有即将到期的链接加密文件。 链接到Nginx的维基
Answer 1:
该接受的答案不正确,因为它只有散列秘密,机密,网址,以及到期时间的不结合。
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
}
Answer 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}")
Answer 3:
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
文章来源: How to generate a nginx secure link in python