-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_cached_data.py
More file actions
65 lines (50 loc) 路 1.61 KB
/
Copy pathread_cached_data.py
File metadata and controls
65 lines (50 loc) 路 1.61 KB
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
55
56
57
58
59
60
61
62
63
64
65
"""
read_cached_data.py
A debugger to read the decrypted cached data.
"""
# ======================================================================
import json
import os
import sys
from pathlib import Path
from cryptography.fernet import Fernet, InvalidToken
# ======================================================================
# yapf: disable
HELP_USAGE = (
f'Usage: python {Path(__file__).name} FILE [OUTPUT_FILE]\n'
'\n'
' Read, unencrypt, and output the given file.'
)
# yapf: enable
# ======================================================================
def main():
# The first arg is this filename
_, *args = sys.argv
if len(args) == 0 or any(arg in ("-h", "--help") for arg in args):
print(HELP_USAGE)
return
filepath = Path(args[0])
if not filepath.exists():
print(f'Error: file "{filepath}" does not exist')
return
decryption_key = os.environ.get("DECRYPTION_KEY", None)
if decryption_key is None:
print("Cannot find decryption key")
return
encoded_data_bytes = filepath.read_bytes()
try:
crypto = Fernet(decryption_key)
decoded_data_bytes = crypto.decrypt(encoded_data_bytes)
except (ValueError, InvalidToken):
print("Error: Invalid decryption key used for stored data")
return
data = json.loads(decoded_data_bytes)
data_str = json.dumps(data, indent=2)
if len(args) >= 2:
output_filepath = Path(args[1])
output_filepath.write_text(data_str, encoding="utf-8")
else:
# print it nicely
print(data_str)
if __name__ == "__main__":
main()