0
0

More than 3 years have passed since last update.

Python3: JWT のペイロード部をデコード

Last updated at Posted at 2021-02-07

こちらのプログラムを Python3 で書き換えました。
Node.js: JWT のペイロード部をデコード

decode_jwt.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   decode_jwt.py
#
#                   Feb/08/2021
#
# ------------------------------------------------------------------
import  sys
import  os
import  json
import  urllib
import  requests
import  base64
#
# ------------------------------------------------------------------
def decodeJWT(str_token):
    sys.stderr.write("len(str_token) = %d\n" % len(str_token))
    aaa = str_token.split(".")
#
    str_bbb = aaa[1].replace("-","+").replace("_","/")
    sys.stderr.write("len(str_bbb) = %d\n" % len(str_bbb))
    ppp = ""
    try:
        str_bbb += "=" * ((4 - len(str_bbb) % 4) % 4)
        ppp = base64.b64decode(str_bbb)
    except Exception as ee:
        sys.stderr.write("*** error *** in b64decode ***\n")
        sys.stderr.write(str(ee) + "\n")
    qqq = urllib.parse.quote(ppp)
    json_str = urllib.parse.unquote(qqq)
#
    return json_str
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
file_token = sys.argv[1]
sys.stderr.write(file_token + "\n")
#
if os.path.exists(file_token):
    try:
        fp_in = open(file_token,encoding='utf-8')
        str_token = fp_in.read()
        fp_in.close()
#
        json_str = decodeJWT(str_token)
        unit_aa = json.loads(json_str)
        print(json_str)
    except Exception as ee:
        sys.stderr.write("*** error *** in jwt.decode ***\n")
        sys.stderr.write(str(ee) + "\n")
#
else:
    sys.stderr.write("*** error *** %s doesn't exist ***\n" % file_token)
#

sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行方法

./decode_jwt.py token01.txt | jq .

参考ページ
‘Incorrect padding’ エラー対処方法.Pythonでbase64を用いてdecode

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0