Overview

ItsDangerous 是一個對資料進行加密簽名的 Python 套件。當需要將資料傳送到不安全的環境時,如果直接將以明碼傳送資料容易被有心人士竊取或竄改。

此時可以將資料先透過自己的金鑰加密,再將加密過的訊息傳送出去,接收方再利用同一份金鑰解密資料,才能查看原始內容。

Usage

Signer - 字串簽名

from itsdangerous import Signer, BadSignature

a = Signer('secret-key')
data = a.sign('this is my send content encrypt by secret-key')
print(data)

result = a.unsign(data)
print(result)

f = Signer('another-key')
try:
    result = f.unsign(data)
except BadSignature:
    print('error')
else:
    print('accept')

t = Signer('secret-key')
try:
    result = t.unsign(data)
except BadSignature:
    print('error')
else:
    print('accept')

輸出 :

b'this is my send content encrypt by secret-key.W-1nh6_P60OP1urd9mw_Us-N--4'
b'this is my send content encrypt by secret-key'
error
accept

TimestampSigner - 時間戳簽名

在簽名內加入時間戳,接收方在接收時就可以判斷使距離發送方發送的時間,來決定是否接受該訊息。

from itsdangerous import TimestampSigner, SignatureExpired
import time
a = TimestampSigner('secret-key')
data = a.sign('this is my send content encrypt by secret-key')
print(data)
try:
    result = a.unsign(data, max_age=5)
except SignatureExpired:
    print('error')
else:
    print('accept')

time.sleep(6)
try:
    result = a.unsign(data, max_age=5)
except SignatureExpired:
    print('error')
else:
    print('accept')

輸出 :

b'this is my send content encrypt by secret-key.YQ4VxQ.RC7oQpar0kUPytM_BZoFabcedSY'
accept
error

Serializer - 序列化

將「可序列化」的物件序列化並簽名

from itsdangerous import Serializer
a = Serializer('secret-key')
info = {'key': 'value'}
data = a.dumps(info)
print(data)

result = a.loads(data)
print(result)

輸出 :

{"key": "value"}.UbkkR9gK-9hD4OUxW_HlyfsvZ-A
{'key': 'value'}

TimedSerializer - 帶有時間戳的序列化