python的模块itsdangerous

这个模块主要用来签名和序列化

使用场景:

一、给字符串添加签名:

  发送方和接收方拥有相同的密钥--"secret-key",发送方使用密钥对发送内容进行签名,接收方使用相同的密钥对接收到的内容进行验证,看是否是发送方发送的内容

 1 >>> from itsdangerous import Signer
 2 >>> s = Signer(‘secret-key‘)
 3 >>> s.sign(‘my string, ssssssssss,dddddddddddddlsd‘)
 4 ‘my string, ssssssssss,dddddddddddddlsd.nSXTxgO_UMN4gkLZcFCioa-dZSo‘
 5 >>>
 6 >>> s.unsign(‘my string, ssssssssss,dddddddddddddlsd.nSXTxgO_UMN4gkLZcFCioa-dZSo‘)
 7 ‘my string, ssssssssss,dddddddddddddlsd‘
 8 >>> s.unsign(‘my string, ssss.nSXTxgO_UMN4gkLZcFCioa-dZSo‘)
 9 Traceback (most recent call last):
10   File "<stdin>", line 1, in <module>
11   File "/usr/local/lib/python2.7/site-packages/itsdangerous.py", line 374, in unsign
12     payload=value)
13 itsdangerous.BadSignature: Signature ‘nSXTxgO_UMN4gkLZcFCioa-dZSo‘ does not match
14 >>> s.unsign(‘my string, ssssssssss,dddddddddddddlsd.nSXTxgO_UMN4gkLZcFCioa-dZSP‘)
15 Traceback (most recent call last):
16   File "<stdin>", line 1, in <module>
17   File "/usr/local/lib/python2.7/site-packages/itsdangerous.py", line 374, in unsign
18     payload=value)
19 itsdangerous.BadSignature: Signature ‘nSXTxgO_UMN4gkLZcFCioa-dZSP‘ does not match
20 >>>

二、带时间戳的签名:

  签名有一定的时效性,发送方发送时,带上时间信息,接收方判断多长时间内是否失效

>>> from itsdangerous import TimestampSigner
>>> s = TimestampSigner(‘secret-key‘)
>>> string = s.sign(‘foo‘)
>>> s.unsign(string, max_age=5)foo>>> s.unsign(string, max_age=5)
Traceback (most recent call last):
  ...
itsdangerous.SignatureExpired: Signature age 15 > 5 seconds

三、序列化

>>> from itsdangerous import Serializer
>>> s = Serializer(‘secret-key‘)
>>> s.dumps([1, 2, 3, 4])
‘[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo‘
And it can of course also load:

>>> s.loads(‘[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo‘)
[1, 2, 3, 4]
If you want to have the timestamp attached you can use the TimedSerializer.

四、带时间戳的序列化:

>>> from itsdangerous import TimedSerializer
>>> s=TimedSerializer(‘secret-key‘)
>>> s.dumps([1,2,3,4])
‘[1, 2, 3, 4].DI7WHQ.yVOjwQWau5mVRGuVkoqa7654VXc‘
>>> s.loads(‘[1, 2, 3, 4].DI7WHQ.yVOjwQWau5mVRGuVkoqa7654VXc‘)
[1, 2, 3, 4]
>>> s.loads(‘[1, 2, 3, 4].DI7WHQ.yVOjwQWau5mVRGuVkoqa7654VXc‘,max_age=10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/itsdangerous.py", line 643, in loads
    .unsign(s, max_age, return_timestamp=True)
  File "/usr/local/lib/python2.7/site-packages/itsdangerous.py", line 463, in unsign
    date_signed=self.timestamp_to_datetime(timestamp))
itsdangerous.SignatureExpired: Signature age 28 > 10 seconds
>>> s.loads(‘[1, 2, 3, 4].DI7WHQ.yVOjwQWau5mVRGuVkoqa7654VXc‘,max_age=40)
[1, 2, 3, 4]
>>>

五、URL安全序列化

对于限定字符串的场景,你可以使用URL安全序列化

>>> from itsdangerous import URLSafeSerializer
>>> s = URLSafeSerializer(‘secret-key‘)
>>> s.dumps([1, 2, 3, 4])
‘WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo‘
>>> s.loads(‘WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo‘)
[1, 2, 3, 4]

六、JSON Web签名

JSON Web Signatures

Starting with “itsdangerous” 0.18 JSON Web Signatures are also supported. They generally work very similar to the already existing URL safe serializer but will emit headers according to the current draft (10) of the JSON Web Signature (JWS) [draft-ietf-jose-json-web-signature].

>>> from itsdangerous import JSONWebSignatureSerializer
>>> s = JSONWebSignatureSerializer(‘secret-key‘)
>>> s.dumps({‘x‘: 42})
‘eyJhbGciOiJIUzI1NiJ9.eyJ4Ijo0Mn0.ZdTn1YyGz9Yx5B5wNpWRL221G1WpVE5fPCPKNuc6UAo‘

When loading the value back the header will not be returned by default like with the other serializers. However it is possible to also ask for the header by passing return_header=True. Custom header fields can be provided upon serialization:

>>> s.dumps(0, header_fields={‘v‘: 1})
‘eyJhbGciOiJIUzI1NiIsInYiOjF9.MA.wT-RZI9YU06R919VBdAfTLn82_iIQD70J_j-3F4z_aM‘
>>> s.loads(‘eyJhbGciOiJIUzI1NiIsInYiOjF9.MA.wT-RZI9YU06R919VBdAf‘
...         ‘TLn82_iIQD70J_j-3F4z_aM‘, return_header=True)
...
(0, {u‘alg‘: u‘HS256‘, u‘v‘: 1})

“itsdangerous” only provides HMAC SHA derivatives and the none algorithm at the moment and does not support the ECC based ones. The algorithm in the header is checked against the one of the serializer and on a mismatch a BadSignatureexception is raised.

七、带时间戳的JSON Web签名

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
s = Serializer(‘secret-key‘, expires_in=60)
s.dumps({‘id‘: user.id}) # user为model中封装过的对象

 

八、盐值

这里的盐值和加密算法里的盐值概念不一样,这里的盐值(salt)可以应用到上面所有情形中,不同的盐值,生成的签名或者序列化的数值不一样

>>> s1 = URLSafeSerializer(‘secret-key‘, salt=‘activate-salt‘)
>>> s1.dumps(42)
‘NDI.kubVFOOugP5PAIfEqLJbXQbfTxs‘
>>> s2 = URLSafeSerializer(‘secret-key‘, salt=‘upgrade-salt‘)
>>> s2.dumps(42)
‘NDI.7lx-N1P-z2veJ7nT1_2bnTkjGTE‘
>>> s2.loads(s1.dumps(42))
Traceback (most recent call last):
  ...
itsdangerous.BadSignature: Signature "kubVFOOugP5PAIfEqLJbXQbfTxs" does not match
Only the serializer with the same salt can load the value:

>>> s2.loads(s2.dumps(42))
42

refer:

1、https://pythonhosted.org/itsdangerous/

2、http://itsdangerous.readthedocs.io/en/latest/

3、http://cxymrzero.github.io/blog/2015/03/18/flask-token/

时间: 2024-07-29 13:31:45

python的模块itsdangerous的相关文章

python之模块ctypes

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块ctypes import ctypes #ctypes是python的一个外部库,它提供了C兼容的数据类型,并允许调用函数C DLL. #注意事项: #就我个人目前而言,了解该库是提供与C语言数据类型兼容的接口作用即可,不需要深入了解.

python shutil模块总结

shutil.copyfile(src,dst)复制文件,如果存在会覆盖 copymode( src, dst)复制权限 copystat(src, dst)复制访问时间和修改时间和权限 copy(src, dst) 复制文件到一个目录 copy2(src, dst)在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了,类似于cp –p的东西 rmtree(path[, ignore_errors[, onerror]])删除文件 move(src, dst)move文件 copyt

python及其模块下载集合

1)python平台 https://www.python.org/downloads/ 2)打包工具 cx-freeze(python3以上版本打包工具) http://cx-freeze.sourceforge.net/ py2exe http://sourceforge.net/projects/py2exe/files/py2exe/ Pyinstaller http://www.pyinstaller.org/ ensymble(电脑端pythonS60打包工具) http://cod

python——常用模块

time.asctime(time.localtime(1234324422)) python--常用模块 1 什么是模块: 模块就是py文件 2 import time #导入时间模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行"type(time.time())",返回的是float类型.

[转]python pickle模块

持久性就是指保持对象,甚至在多次执行同一程序之间也保持对象.通过本文,您会对 Python对象的各种持久性机制(从关系数据库到 Python 的 pickle以及其它机制)有一个总体认识.另外,还会让您更深一步地了解Python 的对象序列化能力. 什么是持久性? 持久性的基本思想很简单.假定有一个 Python 程序,它可能是一个管理日常待办事项的程序,您希望在多次执行这个程序之间可以保存应用程序对象(待办事项).换句话说,您希望将对象存储在磁盘上,便于以后检索.这就是持久性.要达到这个目的,

python之模块py_compile用法(将py文件转换为pyc文件)

# -*- coding: cp936 -*- #python 27 #xiaodeng #python之模块py_compile用法(将py文件转换为pyc文件) #二进制文件,是由py文件经过编译后,生成的文件. ''' import py_compile #不带转义r py_compile.compile('D:\test.py') Traceback (most recent call last): File "<pyshell#1>", line 1, in &l

python之模块pprint之常见用法

# -*- coding: cp936 -*- #python 27 #xiaodeng #python之模块pprint之常见用法 import pprint data = [(1,{'a':'A','b':'B','c':'C','d':'D'}),(2,{'e':'E','f':'F','g':'G','h':'H','i':'I','j':'J','k':'K','l':'L'}),] print '--'*30 #1.打印效果 pprint.pprint (data) ''' ----

python之模块hashlib(提供了常见的摘要算法,如MD5,SHA1等等)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块hashlib(提供了常见的摘要算法,如MD5,SHA1等等) #http://www.cnblogs.com/BeginMan/p/3328172.html #以常见的摘要算法MD5为例,计算出一个字符串的MD5值 import hashlib m = hashlib.md5() #创建hash对象 m.update('xiaodeng') #更新哈希对象以字符串参数 print m.

python之模块ftplib(实现ftp上传下载代码)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块ftplib(实现ftp上传下载代码) #需求:实现ftp上传下载代码(不含错误处理) from ftplib import FTP def ftpconnect(): ftp_server='ftp.python.org' ftp=FTP() ftp.set_debuglevel(2)#打开调式级别2 ftp.connect(ftp_server,21) ftp.login('',''