· 6 years ago · May 12, 2019, 06:54 AM
1import base64
2import hmac
3import hashlib
4import binascii
5
6header ='{"alg":"HS256","typ":"JWT"}'
7payload = '{"loggedInAs":"admin","iat":1422779638}'
8key = "secretkey"
9
10#convert utf-8 string to byte format
11def toBytes(string):
12 return bytes(string,'utf-8')
13
14def encodeBase64(text):
15 return base64.urlsafe_b64encode(text)
16
17#signature = HMAC-SHA256(key, unsignedToken)
18def create_sha256_signature(key, unsignedToken):
19 signature = hmac.new(toBytes(key), unsignedToken, hashlib.sha256).digest()
20 return encodeBase64(signature)
21
22unsignedToken =encodeBase64(toBytes(header)) + toBytes('.') + encodeBase64(toBytes(payload))
23signature =create_sha256_signature(key,unsignedToken)
24
25#remove "=" sign,
26#P.S. "=" sign is used only as a complement in the final process of encoding a message.
27jwt_toekn=unsignedToken.decode("utf-8") +'.'+signature.decode("utf-8").replace("=",'')
28print(jwt_toekn)