Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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")