import jwt
import base64
key = 'user_id_KEY'
payload = {'user_id': '1'}
token = jwt.encode(payload, key, algorithm='HS256')
print('1.token is {}'.format(token))
s = token.split(b'.') #点分三段,补齐bytes打印
for i in s:
x = 4-len(i)%4
if x == 4:
print(base64.b64decode(i))
else:
i = i + x * b'='
print(base64.b64decode(i))
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
# b'{"typ":"JWT","alg":"HS256"}'
# b'{"user_id":"1"}'
# b'\x98\xd5&\xe0\x1b-~2%Nk\x1c\xdeg\xdf\xa2V\xec<{^\xcb0q=\x0e\xd94z\x94'
#可以看出token组成有三部分,head和payload其实并未加密,只做了base64编码,第三部分token的签名
#接下来,我们来看看第三部分的秘密
#由于哈希算法的不可逆性,我们可以试着找出被哈希的部分,用key加哈希算法计算
from jwt import algorithms
alg = algorithms.get_default_algorithms()['HS256']
#取head
signature = alg.sign(s[0], key.encode())
print(signature)
print('one test->{}'.format(base64.b64encode(signature)))
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
#取payload
signature = alg.sign(s[1], key.encode())
print(signature)
print('two test->{}'.format(base64.b64encode(signature)))
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
#取head+payload,别忘记加.
signature = alg.sign(s[0] + b'.' + s[1], key.encode())
print(signature)
print('three test->{}'.format(base64.b64encode(signature)))
"""
输出结果
1.token is b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMSJ9.mNUm4BstfjIlTmsc3mffolbsPH-teyz-BxPQ7ZN-HqU'
b'{"typ":"JWT","alg":"HS256"}'
b'{"user_id":"1"}'
b'\x98\xd5&\xe0\x1b-~2%Nk\x1c\xdeg\xdf\xa2V\xec<{^\xcb0q=\x0e\xd94z\x94'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
b'\xa3u4C\xf9XT/X\x80\x14\xee\x82$%\x820m2+\xb0b\t\xd4\xe8\xdf\xfb_\x9c\xeeH\xe3'
one test->b'o3U0Q/lYVC9YgBTugiQlgjBtMiuwYgnU6N/7X5zuSOM='
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
b'\xef<\xf1\x80`\xd0\xb0_\r\x19:\xd5E\x0f\xe8\xc9\xe6\x98\x16\x85\x8a\xa4\xaa\xff\xdco\xedu\xbb\xf7\xccM'
two test->b'7zzxgGDQsF8NGTrVRQ/oyeaYFoWKpKr/3G/tdbv3zE0='
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
b'\x98\xd5&\xe0\x1b-~2%Nk\x1c\xdeg\xdf\xa2V\xec<\x7f\xad{,\xfe\x07\x13\xd0\xed\x93~\x1e\xa5'
three test->b'mNUm4BstfjIlTmsc3mffolbsPH+teyz+BxPQ7ZN+HqU='
"""