import argparse import sys import logging import base64 from jose import jws from pathlib import Path import json if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='count', help='Verbose logging (can be specified multiple times)') parser.add_argument('-i', '--input', type=argparse.FileType('r'), default=sys.stdin, help="Path to input file (if absent, stdin is used)") args = parser.parse_args() match args.verbose: case v if v and v >= 2: logging.basicConfig(level=logging.DEBUG) case 1: logging.basicConfig(level=logging.INFO) case _: logging.basicConfig(level=logging.WARNING) logging.debug(f"Arguments: {args}") signed_json_text = args.input.read() args.input.close() j = json.loads(signed_json_text) protected_header = j['Signature']['protected'] signature = j['Signature']['signature'] # TODO some safety checks needed here # Remove the newline that appears from the console if signed_json_text.endswith('\n'): signed_json_text = signed_json_text[:-1] signed_json_text = signed_json_text.replace(protected_header, "").replace(signature, "") payload_bytes = signed_json_text.encode('utf-8') payload_token = base64.b64encode(payload_bytes).decode('ascii') # Un-pad the token, as per RFC7515 annex C payload_token = payload_token.split('=')[0] payload_token = payload_token.replace('+','-') payload_token = payload_token.replace('/','_') token = protected_header + "." + payload_token + "." + signature result = jws.verify(token, key="secret_key", algorithms=['HS256']) print("Signature verified")