-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencrypt.py
More file actions
127 lines (106 loc) · 3.71 KB
/
Copy pathencrypt.py
File metadata and controls
127 lines (106 loc) · 3.71 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import ujson
import os
'''
Простенький шифрувальник, потрібно створити файл variables.env в якому визначити значення для secret_key, наприклад "MySecretKey123"
Зміни назву на свій CONFIG_FILE
'''
ENV_FILE = "variables.env"
ENV_VAR_NAME = "secret_key"
def _get_secret_key():
"""
Function for search secret_key in file variables.env.
"""
try:
with open(ENV_FILE, "r") as f:
for line in f:
line = line.strip()
# Pass comments
if not line or line.startswith("#"):
continue
if "=" in line:
key, value = line.split("=", 1)
if key.strip() == ENV_VAR_NAME:
return value.strip().strip('"').strip("'")
except OSError:
print(f"[Error]: file {ENV_FILE} does not founded!")
print(f"[Error]: key {ENV_VAR_NAME} does not founded!")
return None
def get_env_value(in_file, in_key):
"""
Function for search secret_key in file variables.env.
"""
try:
with open(in_file, "r") as f:
for line in f:
line = line.strip()
# Pass comments
if not line or line.startswith("#"):
continue
if "=" in line:
key, value = line.split("=", 1)
if key.strip() == in_key:
return value.strip().strip('"').strip("'")
except OSError:
print(f"[Error]: file {in_file} does not founded!")
print(f"[Error]: key {in_key} does not founded!")
return None
def _xor_cipher(data_bytes, key_str):
"""XOR encrypting/decrypting"""
if not key_str:
return data_bytes
key_bytes = key_str.encode('utf-8')
key_len = len(key_bytes)
result = bytearray(len(data_bytes))
for i in range(len(data_bytes)):
result[i] = data_bytes[i] ^ key_bytes[i % key_len]
return result
def save_config(data_dict, config_flie):
"""Save current config in ecrypted version"""
key = _get_secret_key()
if not key:
return False
try:
json_str = ujson.dumps(data_dict)
encrypted_data = _xor_cipher(json_str.encode('utf-8'), key)
with open(config_flie, "wb") as f:
f.write(encrypted_data)
print(f"[OK] Saved and encrypted {config_flie}")
return True
except Exception as e:
print(f"[ERROR] Can't save config: {e}")
return False
def load_config(config_flie):
"""Load encrypted file and decrypt him"""
key = _get_secret_key()
if not key:
return None
try:
with open(config_flie, "rb") as f:
file_data = f.read()
try:
return ujson.loads(file_data)
except ValueError:
pass
decrypted_data = _xor_cipher(file_data, key)
json_str = decrypted_data.decode('utf-8')
return ujson.loads(json_str)
except OSError:
print(f"[INFO] File {config_flie} still exist.")
return None
except Exception as e:
print(f"[ERROR] Reading/encrypting error: {e}")
return None
def encrypt_existing_file(config_flie):
"""
Utillity to encrypt existing non-crypted config.json file
"""
print("encrypt_existing_file() begin")
try:
with open(config_flie, "r") as f:
data = ujson.load(f)
if save_config(data):
print("File saved in encrypted fromat")
except ValueError:
print("File encrypted or invalid")
except OSError:
print("No file")