Skip to content

Instantly share code, notes, and snippets.

@ixe013
Last active September 14, 2023 18:23
Show Gist options
  • Save ixe013/f3a7ca48e327a7652554f29be3ee7d46 to your computer and use it in GitHub Desktop.
Save ixe013/f3a7ca48e327a7652554f29be3ee7d46 to your computer and use it in GitHub Desktop.
Python script to decode a JWT. Works with JWT that are compressed (DEFLATE algorihtm) and incomplete padding
from __future__ import print_function
import base64
import json
import os.path
import pprint
import sys
import time
import zlib
def pad_base64(data):
"""Makes sure base64 data is padded
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += '='* (4 - missing_padding)
return data
def decompress_partial(data):
"""Decompress arbitrary deflated data. Works even if header and footer is missing
"""
decompressor = zlib.decompressobj()
return decompressor.decompress(data)
def decompress(JWT):
"""Split a JWT to its constituent parts.
Decodes base64, decompress if required. Returns but does not validate the signature.
"""
header, jwt, signature = JWT.split('.')
printable_header = base64.urlsafe_b64decode(pad_base64(header)).decode('utf-8')
if json.loads(printable_header).get("zip", "").upper() == "DEF":
printable_jwt = decompress_partial(base64.urlsafe_b64decode(pad_base64(jwt)))
else:
printable_jwt = base64.urlsafe_b64decode(pad_base64(jwt)).decode('utf-8')
printable_signature = base64.urlsafe_b64decode(pad_base64(signature))
return json.loads(printable_header), json.loads(printable_jwt), printable_signature
def showJWT(JWT):
header, jwt, signature = decompress(JWT)
print("Header: ", end="")
pprint.pprint(header)
print("Token: ", end="")
pprint.pprint(jwt)
print("Issued at: {} (localtime)".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(jwt['iat'])) if 'iat' in jwt else 'Undefined'))
print("Not before: {} (localtime)".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(jwt['nbf'])) if 'nbf' in jwt else 'Undefined'))
print("Expiration: {} (localtime)".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(jwt['exp'])) if 'exp' in jwt else 'Undefined'))
if __name__ == "__main__":
if len(sys.argv) > 1:
jwt = sys.argv[1]
if os.path.exists(jwt):
with open(sys.argv[1], "r") as input_file:
jwt = input_file.read().strip()
showJWT(jwt)
@MohRaza
Copy link

MohRaza commented Aug 9, 2021

In case someone is wondering how to use this script with "shc:/12496934958......238484329" string that the Vaccine QR Code gives, the following code can be used:

qrcode="shc:/12496934958......238484329"
raw="12496934958......238484329"
jwt = ""
for (char1, char2) in zip(raw[0::2], raw[1::2]):
            jwt = jwt + chr(int(char1+char2)+45)
# jwt = "eyJ6aXAiOi...."

@MohRaza
Copy link

MohRaza commented Aug 9, 2021

Another thing worth mentioning, if the decoded json payload contains French characters (e.g. SiteName... "VACCINATION À L'AUTO..."), then pprint library will throw an error, and if you print json payload without using pprint library, you will see the french character in unicode (e.g. VACCINATION \u00c0 L'AUTO).

@hotcobra
Copy link

hotcobra commented Aug 9, 2021

I'm no Python expert but shouldn't the final JWS be numerically encoded? (Smarthealthcard: "the JWS string SHALL be encoded as Numerical Mode QR codes consisting of the digits 0-9") Or was this what MohRaza is referring to?

@MohRaza
Copy link

MohRaza commented Aug 9, 2021

JWT Tokens are three base64 strings concatenated with a "." as described by the official spec https://jwt.io/.

SmartHealthCard (SHC) is numerically encoded JWT prepended with "shc:/". A SmartHealthCard QR Code is the "shc:/123456....123456" string encoded as a QR Code.

@MohRaza
Copy link

MohRaza commented Aug 9, 2021

And JWT is numerically encoded by taking the ASCII value of the JWT token's base64 characters, and subtracting 45 from it. Therefore when converting shc:/123456...123432 to JWT, you take two digits at a time, add 45 to the digits, and use ASCII mapping to get the corresponding base64 character.

@sdomi003
Copy link

thanks, this is very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment