-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyWave.py
424 lines (316 loc) · 12.9 KB
/
pyWave.py
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#################### Imports & Definitions ####################
import os
import sqlite3
import beaupy
from datetime import datetime
from pystyle import Colors, Colorate
import json
import base64
from Crypto.Cipher import ChaCha20_Poly1305
from Crypto.Random import get_random_bytes
import gcm
import binascii
import csv
import secrets
import string
from decimal import Decimal
chacha_header = b"ChaCha real smooth~ dada da dada da"
salt = get_random_bytes(32)
#################### Imports & Definitions ####################
#################### Functions ####################
def banner():
banner = """
::::::::: ::: ::: ::: ::: ::: ::: ::: ::::::::::
:+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
+:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+
+#++:++#+ +#++: +#+ +:+ +#+ +#++:++#++: +#+ +:+ +#++:++#
+#+ +#+ +#+ +#+#+ +#+ +#+ +#+ +#+ +#+ +#+
#+# #+# #+#+# #+#+# #+# #+# #+#+#+# #+#
### ### ### ### ### ### ### ##########
Made by Ori#6338 | @therealOri_ | https://github.com/therealOri
"""
colored_banner = Colorate.Horizontal(Colors.purple_to_blue, banner, 1)
return colored_banner
def clear():
os.system("clear||cls")
def load_config():
with open('config.json') as f:
config = json.load(f)
database = config.get('database')
if not database:
clear()
input('Invalid config: "database in config.json is empty or missing."\n\nPress "enter" to exit...')
exit()
if os.path.isfile(config["database"]) or os.path.isfile(f'{config["database"]}.locked'):
return config
else:
clear()
input('Error loading config file: "Provided database in config.json does not exist."\n\nPress "enter" to exit...')
exit()
def add_action(price, operation, desc):
now = datetime.now()
date = now.strftime("%m/%d/%Y")
time = now.strftime("%I:%M:%S %p")
conn = sqlite3.connect(config["database"])
c = conn.cursor()
c.execute("INSERT INTO transactions (price, operation, description, date, time) VALUES (?, ?, ?, ?, ?)", (price, operation.lower(), desc, date, time))
conn.commit()
conn.close()
def update_total():
conn = sqlite3.connect(config["database"])
c = conn.cursor()
c.execute("SELECT price FROM transactions ORDER BY id DESC LIMIT 1")
last_price = c.fetchone()[0]
c.execute("SELECT operation FROM transactions ORDER BY id DESC LIMIT 1")
last_operation = c.fetchone()[0]
c.execute("SELECT total FROM transactions")
current_total = c.fetchall()
try:
current_total = current_total[-2][0]
except:
current_total = current_total[0][0]
if last_operation == "in":
new_total = current_total + last_price
elif last_operation == "out":
if current_total == 0.0:
c.execute("DELETE FROM transactions WHERE id = (SELECT MAX(id) FROM transactions);")
c.execute("DELETE FROM sqlite_sequence WHERE name = 'transactions';")
conn.commit()
conn.close()
return None
else:
new_total = current_total - last_price
c.execute("UPDATE transactions SET total = ? WHERE id = (SELECT MAX(id) FROM transactions)", (new_total,))
conn.commit()
conn.close()
return True
def view_balance():
conn = sqlite3.connect(config["database"])
c = conn.cursor()
c.execute("SELECT total FROM transactions")
transactions = c.fetchall()
try:
current_total = Decimal(str(transactions[-1][0])).quantize(Decimal('.01'))
except:
current_total = Decimal('0.00')
return current_total
def lock(plaintext, eKey):
data_enc = gcm.stringE(enc_data=plaintext, key=eKey)
data_enc = bytes(data_enc, 'utf-8')
cipher = ChaCha20_Poly1305.new(key=salt)
cipher.update(chacha_header)
ciphertext, tag = cipher.encrypt_and_digest(data_enc)
jk = [ 'nonce', 'header', 'ciphertext', 'tag' ]
jv = [ base64.b64encode(x).decode('utf-8') for x in (cipher.nonce, chacha_header, ciphertext, tag) ]
result = json.dumps(dict(zip(jk, jv)))
result_bytes = bytes(result, 'utf-8')
b64_result = base64.b64encode(result_bytes)
final_result = base64_to_hex(b64_result)
return final_result
def unlock(dKey, json_input, salt):
try:
b64 = json.loads(json_input)
jk = [ 'nonce', 'header', 'ciphertext', 'tag' ]
jv = {k:base64.b64decode(b64[k]) for k in jk}
cipher = ChaCha20_Poly1305.new(key=salt, nonce=jv['nonce'])
cipher.update(jv['header'])
plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
except (ValueError, KeyError):
print("Incorrect decryption credentials, or data has been tampered with.")
return None
decrypted_message = gcm.stringD(dcr_data=plaintext, key=dKey)
return decrypted_message
def base64_to_hex(base64_string):
decoded_bytes = base64.b64decode(base64_string)
hex_string = binascii.hexlify(decoded_bytes)
return hex_string.decode()
def hex_to_base64(hex_string):
hex_bytes = bytes.fromhex(hex_string)
base64_string = base64.b64encode(hex_bytes)
return base64_string.decode()
def generate_filename(length, ext):
alphabet = string.ascii_letters + string.digits
filename = ''.join(secrets.choice(alphabet) for i in range(length)) + ext
return filename
def export_to_csv():
conn = sqlite3.connect(config["database"])
c = conn.cursor()
c.execute("SELECT * FROM transactions")
data = c.fetchall()
c.execute(f"PRAGMA table_info(transactions)")
column_names = [column[1] for column in c.fetchall()]
csv_file_name = generate_filename(12, '.csv')
with open(csv_file_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(column_names)
writer.writerows(data)
conn.close()
return csv_file_name
def create_db(new_db_name):
conn = sqlite3.connect(f"{new_db_name}.db")
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
price REAL,
operation TEXT,
description TEXT,
date TEXT,
time TEXT,
total REAL DEFAULT 0
)""")
conn.commit()
conn.close()
#################### Functions ####################
#################### Main ####################
def main():
while True:
options = ["Make Transaction?", "View balance?", "Lock database?", "Export to CSV?", "Make new database?", "Exit?"]
print(f'{banner()}\n\nWhat would you like to do?\n-----------------------------------------------------------\n')
option = beaupy.select(options, cursor_style="#ffa533")
if not option:
clear()
exit("Keyboard Interuption Detected!\nGoodbye <3")
if options[0] in option:
if os.path.isfile(f'{config["database"]}.locked'):
clear()
print("Database file does not exist or is encrypted...")
input('\n\nPress "enter" to continue...')
clear()
continue
else:
clear()
price = beaupy.prompt("Transaction Ammount.")
if not price:
clear()
continue
try:
price = float(price)
except Exception as e:
input(f'"price" is not a float.\n{e}\n\nPress "enter" to continue...')
clear()
continue
operation = beaupy.prompt("In or Out?").lower()
if not operation:
clear()
continue
while operation not in ["in", "out"]:
operation = beaupy.prompt("Invalid input. In or Out?").lower()
desc = beaupy.prompt("Description for transaction.")
if not desc:
clear()
continue
add_action(price, operation, desc)
check = update_total()
if check == None:
input('Transaction has NOT been made as current_total is 0.0 and you have no money to take out.\n\nPress "enter" to contine...')
clear()
continue
else:
input('Transaction has been made.\n\nPress "enter" to contine...')
clear()
continue
if options[1] in option:
if os.path.isfile(f'{config["database"]}.locked'):
clear()
print("Database file does not exist or is encrypted...")
input('\n\nPress "enter" to continue...')
clear()
continue
else:
clear()
balance = view_balance()
input(f'Total available balance: ${balance}\n\nPress "enter" to continue...')
clear()
if options[2] in option:
if os.path.isfile(f'{config["database"]}.locked'):
clear()
print("Database file is already encrypted...")
input('\n\nPress "enter" to continue...')
clear()
continue
else:
clear()
file_name = config["database"]
key_data = beaupy.prompt("Data for key gen - (100+ characters)").encode()
clear()
eKey = gcm.keygen(key_data)
if not eKey:
continue
save_me = base64.b64encode(eKey)
bSalt = base64.b64encode(salt)
master_key = f"{save_me.decode()}:{bSalt.decode()}"
input(f'Save this key so you can decrypt later: {master_key}\n\nPress "enter" to contine...')
clear()
with open(file_name, 'rb') as rb:
data = rb.read()
chaCrypt = lock(data, eKey)
clear()
with open(file_name, 'w') as fw:
fw.write(chaCrypt)
os.rename(file_name, file_name.replace(file_name, f'{file_name}.locked'))
input('Database has been locked!\n\nPress "enter" to exit...')
clear()
exit("Goodbye! <3")
if options[3] in option:
if os.path.isfile(f'{config["database"]}.locked'):
clear()
print("Database file does not exist or is encrypted...")
input('\n\nPress "enter" to continue...')
clear()
continue
else:
exported_file = export_to_csv()
input(f'Database transactions have been exported to "{exported_file}".\n\nPress "enter" to continue...')
clear()
continue
if options[4] in option:
clear()
db_name = beaupy.prompt('New name for the database. - "new_db_name"')
create_db(db_name)
clear()
input(f'New databse has been made called "{db_name}.db". You can use it by updating the config.json file.\n\nPress "enter" to exit...')
clear()
exit()
if options[5] in option:
clear()
exit("Goodbye! <3")
#################### Main ####################
if __name__ == '__main__':
config = load_config()
enc_file_name = f'{config["database"]}.locked'
if os.path.isfile(enc_file_name):
clear()
while True:
print("Database is locked. Please provide the key to unlock the database.")
dKey = beaupy.prompt("Encryption Key", secure=True)
if not dKey:
input("Please provide a key to unlock the database.")
clear()
continue
clear()
break
with open(enc_file_name, 'r') as fr:
dData = fr.read()
enc_data = hex_to_base64(dData)
try:
json_input = base64.b64decode(enc_data)
key_and_salt = dKey.split(":")
enc_salt = key_and_salt[1]
enc_key = key_and_salt[0]
except:
input('The "key" that was given is not a valid key.\n\nPress "enter" to try again...')
clear()
exit()
dsalt = base64.b64decode(enc_salt)
dkey = base64.b64decode(enc_key)
cha_aes_crypt = unlock(dkey, json_input, dsalt)
with open(enc_file_name, 'wb') as fw:
fw.write(cha_aes_crypt)
os.rename(enc_file_name, enc_file_name.replace('.locked', ''))
clear()
input('Database unlocked!\n\nPress "enter" to continue...')
clear()
main()
else:
clear()
main()