首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中生成nginx安全链接

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

Stack Overflow用户
提问于 2012-07-23 19:55:31
回答 3查看 5.1K关注 0票数 1

如何在nginx中使用python制作安全链接模块的链接?我希望使用nginx为有过期链接的安全文件提供服务。Link to Nginx Wiki

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-23 19:55:31

代码语言:javascript
复制
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是您生成的表单url:

代码语言:javascript
复制
/securedir/file.txt?st=PIrEk4JX5gJPTGmvqJG41g&e=1324527723
票数 -1
EN

Stack Overflow用户

发布于 2018-10-11 23:58:05

shadfc答案中的代码可以工作。对于Python 3,需要做一些修改:

代码语言:javascript
复制
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}")
票数 5
EN

Stack Overflow用户

发布于 2015-03-15 04:56:14

可接受的答案是不正确的,因为它只散列密钥,而不是密钥、url和过期时间的组合。

代码语言:javascript
复制
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的相应部分

代码语言:javascript
复制
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
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11612032

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档