jwt

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成有三部分,headpayload实并未加密,只做了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='
"""

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值