-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1177 lines (968 loc) · 50.1 KB
/
Copy pathmain.py
File metadata and controls
1177 lines (968 loc) · 50.1 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
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
File Hash Generator and Verifier
A Python application with GUI for computing and verifying file hashes.
Enhanced version with comprehensive algorithms and better UI.
"""
import os
import sys
import json
import hashlib
import threading
import time
import zlib
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, List, Tuple, Optional, Callable
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
from datetime import datetime
# Try to import additional hash libraries
try:
import xxhash
XXHASH_AVAILABLE = True
except ImportError:
XXHASH_AVAILABLE = False
try:
import blake3
BLAKE3_AVAILABLE = True
except ImportError:
BLAKE3_AVAILABLE = False
class HashGenerator:
"""Core class for hash generation and verification operations."""
def __init__(self):
self.stop_event = threading.Event()
self.SUPPORTED_ALGORITHMS = self._get_supported_algorithms()
def _get_supported_algorithms(self):
"""Get all supported hash algorithms."""
algorithms = {
'MD5': lambda: hashlib.md5(),
'SHA1': lambda: hashlib.sha1(),
'SHA-3': lambda: hashlib.sha3_256(),
'SHA256': lambda: hashlib.sha256(),
'SHA512': lambda: hashlib.sha512(),
'xxHash64': lambda: xxhash.xxh64() if XXHASH_AVAILABLE else None,
'Blake2b': lambda: hashlib.blake2b(),
'Blake3': lambda: blake3.blake3() if BLAKE3_AVAILABLE else None,
'CRC32': lambda: None, # Special case - handled separately
}
# Filter out unavailable algorithms
available = {}
for name, func in algorithms.items():
if name == 'CRC32':
available[name] = func
else:
try:
test = func()
if test is not None:
available[name] = func
except:
continue
return available
def calculate_file_hash(self, file_path: str, algorithm: str = 'SHA256',
chunk_size: int = 8192) -> Optional[str]:
"""Calculate hash for a single file."""
try:
if algorithm not in self.SUPPORTED_ALGORITHMS:
raise ValueError(f"Unsupported algorithm: {algorithm}")
# Special handling for CRC32
if algorithm == 'CRC32':
crc = 0
with open(file_path, 'rb') as f:
while chunk := f.read(chunk_size):
if self.stop_event.is_set():
return None
crc = zlib.crc32(chunk, crc)
return f"{crc & 0xffffffff:08x}"
# Handle xxHash
if algorithm == 'xxHash64' and XXHASH_AVAILABLE:
hasher = xxhash.xxh64()
with open(file_path, 'rb') as f:
while chunk := f.read(chunk_size):
if self.stop_event.is_set():
return None
hasher.update(chunk)
return hasher.hexdigest()
# Handle Blake3
if algorithm == 'Blake3' and BLAKE3_AVAILABLE:
hasher = blake3.blake3()
with open(file_path, 'rb') as f:
while chunk := f.read(chunk_size):
if self.stop_event.is_set():
return None
hasher.update(chunk)
return hasher.hexdigest()
# Standard hashlib algorithms
hash_func = self.SUPPORTED_ALGORITHMS[algorithm]()
with open(file_path, 'rb') as f:
while chunk := f.read(chunk_size):
if self.stop_event.is_set():
return None
hash_func.update(chunk)
return hash_func.hexdigest()
except (IOError, OSError, PermissionError) as e:
print(f"Error reading file {file_path}: {e}")
return None
except Exception as e:
print(f"Unexpected error processing {file_path}: {e}")
return None
def scan_location(self, location: str, algorithm: str = 'SHA256',
progress_callback: Optional[Callable] = None,
max_workers: int = 4) -> Tuple[Dict[str, str], List[str]]:
"""Scan a location and calculate hashes for all files."""
results = {}
error_files = []
file_list = []
# Collect all files
try:
if os.path.isfile(location):
file_list = [location]
elif os.path.isdir(location):
for root, dirs, files in os.walk(location):
if self.stop_event.is_set():
break
for file in files:
file_path = os.path.join(root, file)
if os.path.isfile(file_path):
file_list.append(file_path)
except Exception as e:
print(f"Error scanning location {location}: {e}")
return results, [f"Scan error: {str(e)}"]
total_files = len(file_list)
if total_files == 0:
return results, error_files
# Process files with threading
completed_files = 0
with ThreadPoolExecutor(max_workers=max_workers) as executor:
# Submit all tasks
future_to_file = {
executor.submit(self.calculate_file_hash, file_path, algorithm): file_path
for file_path in file_list
}
# Process completed tasks
for future in as_completed(future_to_file):
if self.stop_event.is_set():
break
file_path = future_to_file[future]
try:
hash_value = future.result()
if hash_value:
results[file_path] = hash_value
else:
error_files.append(file_path)
except Exception as e:
print(f"Error processing {file_path}: {e}")
error_files.append(f"{file_path} - Error: {str(e)}")
completed_files += 1
if progress_callback:
progress_callback(completed_files, total_files, file_path)
return results, error_files
def save_hashes(self, hash_data: Dict[str, str], error_files: List[str],
output_file: str, algorithm: str, scan_location: str) -> bool:
"""Save hash data and errors to files."""
try:
# Prepare main data
data = {
'metadata': {
'algorithm': algorithm,
'scan_location': scan_location,
'timestamp': datetime.now().isoformat(),
'total_files': len(hash_data),
'error_files': len(error_files),
'application': 'File Hash Generator v2.0'
},
'hashes': {},
'errors': error_files
}
# Convert paths and add file info
base_path = os.path.dirname(scan_location) if os.path.isfile(scan_location) else scan_location
for file_path, hash_value in hash_data.items():
try:
rel_path = os.path.relpath(file_path, base_path)
except ValueError:
rel_path = file_path
file_size = 0
file_mtime = 0
try:
stat = os.stat(file_path)
file_size = stat.st_size
file_mtime = stat.st_mtime
except:
pass
data['hashes'][rel_path] = {
'hash': hash_value,
'full_path': file_path,
'size': file_size,
'modified': file_mtime
}
# Save main hash file
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# Save separate error file if there are errors
if error_files:
error_file = output_file.replace('.json', '_errors.txt')
with open(error_file, 'w', encoding='utf-8') as f:
f.write(f"Error Report - {datetime.now().isoformat()}\n")
f.write(f"Scan Location: {scan_location}\n")
f.write(f"Algorithm: {algorithm}\n\n")
f.write("Files with errors:\n")
f.write("=" * 50 + "\n")
for error in error_files:
f.write(f"{error}\n")
return True
except Exception as e:
print(f"Error saving hashes: {e}")
return False
def load_hashes(self, hash_file: str) -> Optional[Dict]:
"""Load hash data from a file."""
try:
with open(hash_file, 'r', encoding='utf-8') as f:
data = json.load(f)
# Validate structure
if 'metadata' not in data or 'hashes' not in data:
raise ValueError("Invalid hash file format")
return data
except Exception as e:
print(f"Error loading hashes: {e}")
return None
def verify_integrity(self, hash_file: str, base_path: str = None,
progress_callback: Optional[Callable] = None) -> Tuple[Dict[str, str], List[str], List[str]]:
"""Verify file integrity against saved hashes."""
hash_data = self.load_hashes(hash_file)
if not hash_data:
return {}, [], ["Failed to load hash file"]
algorithm = hash_data['metadata']['algorithm']
hashes = hash_data['hashes']
results = {}
corrupted_files = []
error_files = []
total_files = len(hashes)
completed_files = 0
for rel_path, file_info in hashes.items():
if self.stop_event.is_set():
break
stored_hash = file_info['hash']
full_path = file_info.get('full_path', '')
# Determine actual file path
current_path = None
if base_path and os.path.exists(os.path.join(base_path, rel_path)):
current_path = os.path.join(base_path, rel_path)
elif os.path.exists(full_path):
current_path = full_path
elif os.path.exists(rel_path):
current_path = rel_path
if not current_path:
results[rel_path] = "FILE_NOT_FOUND"
error_files.append(f"{rel_path} - File not found")
completed_files += 1
if progress_callback:
progress_callback(completed_files, total_files, rel_path)
continue
# Calculate current hash
try:
current_hash = self.calculate_file_hash(current_path, algorithm)
if current_hash is None:
results[rel_path] = "READ_ERROR"
error_files.append(f"{rel_path} - Unable to read file")
elif current_hash == stored_hash:
results[rel_path] = "MATCH"
else:
results[rel_path] = "MISMATCH"
corrupted_files.append({
'path': current_path,
'relative_path': rel_path,
'stored_hash': stored_hash,
'current_hash': current_hash,
'algorithm': algorithm
})
except Exception as e:
results[rel_path] = "VERIFICATION_ERROR"
error_files.append(f"{rel_path} - Verification error: {str(e)}")
completed_files += 1
if progress_callback:
progress_callback(completed_files, total_files, current_path)
return results, corrupted_files, error_files
def save_verification_report(self, results: Dict[str, str], corrupted_files: List[Dict],
error_files: List[str], output_file: str, hash_file: str) -> bool:
"""Save verification report with corrupted files details."""
try:
report = {
'metadata': {
'verification_time': datetime.now().isoformat(),
'source_hash_file': hash_file,
'total_files_checked': len(results),
'corrupted_files': len(corrupted_files),
'error_files': len(error_files),
'application': 'File Hash Generator v2.0'
},
'summary': {
'matches': sum(1 for r in results.values() if r == 'MATCH'),
'mismatches': sum(1 for r in results.values() if r == 'MISMATCH'),
'not_found': sum(1 for r in results.values() if r == 'FILE_NOT_FOUND'),
'read_errors': sum(1 for r in results.values() if r == 'READ_ERROR'),
'verification_errors': sum(1 for r in results.values() if r == 'VERIFICATION_ERROR')
},
'detailed_results': results,
'corrupted_files': corrupted_files,
'errors': error_files
}
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(report, f, indent=2, ensure_ascii=False)
# Save separate corrupted files list if any
if corrupted_files:
corrupted_file = output_file.replace('.json', '_corrupted.txt')
with open(corrupted_file, 'w', encoding='utf-8') as f:
f.write(f"Corrupted Files Report - {datetime.now().isoformat()}\n")
f.write(f"Source: {hash_file}\n")
f.write(f"Total corrupted files: {len(corrupted_files)}\n\n")
for i, file_info in enumerate(corrupted_files, 1):
f.write(f"{i}. {file_info['relative_path']}\n")
f.write(f" Full Path: {file_info['path']}\n")
f.write(f" Algorithm: {file_info['algorithm']}\n")
f.write(f" Expected: {file_info['stored_hash']}\n")
f.write(f" Actual: {file_info['current_hash']}\n\n")
return True
except Exception as e:
print(f"Error saving verification report: {e}")
return False
def stop_operation(self):
"""Stop current operation."""
self.stop_event.set()
def reset_stop_event(self):
"""Reset stop event for new operations."""
self.stop_event.clear()
class ModernHashGeneratorGUI:
"""Modern GUI for the File Hash Generator and Verifier."""
def __init__(self, root):
self.root = root
self.root.title("File Hash Generator & Verifier v2.0")
self.root.geometry("900x700")
self.root.minsize(800, 600)
# Set modern colors
self.colors = {
'bg': '#f0f0f0',
'primary': '#2E86AB',
'secondary': '#A23B72',
'success': '#2E8B57',
'warning': '#FF8C00',
'error': '#DC143C',
'text': '#2F4F4F'
}
self.hash_generator = HashGenerator()
self.current_operation = None
self.hash_results = {}
self.error_files = []
self.setup_styles()
self.setup_gui()
def setup_styles(self):
"""Setup modern ttk styles."""
style = ttk.Style()
# Configure modern theme
style.theme_use('clam')
# Custom button styles
style.configure('Modern.TButton',
font=('Segoe UI', 10),
borderwidth=1,
focuscolor='none')
style.configure('Primary.TButton',
background=self.colors['primary'],
foreground='white',
font=('Segoe UI', 10, 'bold'),
borderwidth=0)
style.map('Primary.TButton',
background=[('active', '#1E5F73')])
style.configure('Success.TButton',
background=self.colors['success'],
foreground='white',
font=('Segoe UI', 10, 'bold'))
style.configure('Warning.TButton',
background=self.colors['warning'],
foreground='white',
font=('Segoe UI', 10, 'bold'))
style.configure('Error.TButton',
background=self.colors['error'],
foreground='white',
font=('Segoe UI', 10, 'bold'))
# Custom frame styles
style.configure('Card.TFrame',
background='white',
relief='solid',
borderwidth=1)
# Custom labelframe style
style.configure('Modern.TLabelframe',
background='white',
font=('Segoe UI', 10, 'bold'))
style.configure('Modern.TLabelframe.Label',
background='white',
foreground=self.colors['primary'],
font=('Segoe UI', 10, 'bold'))
# Progress bar style
style.configure('Modern.Horizontal.TProgressbar',
background=self.colors['primary'],
troughcolor='#E0E0E0',
borderwidth=0,
lightcolor=self.colors['primary'],
darkcolor=self.colors['primary'])
def setup_gui(self):
"""Setup the modern GUI layout."""
# Configure root
self.root.configure(bg=self.colors['bg'])
# Header
header_frame = tk.Frame(self.root, bg=self.colors['primary'], height=60)
header_frame.pack(fill=tk.X, pady=(0, 10))
header_frame.pack_propagate(False)
title_label = tk.Label(header_frame,
text="File Hash Generator & Verifier",
bg=self.colors['primary'],
fg='white',
font=('Segoe UI', 16, 'bold'))
title_label.pack(expand=True)
subtitle_label = tk.Label(header_frame,
text="Secure file integrity checking with modern algorithms",
bg=self.colors['primary'],
fg='#B8E0FF',
font=('Segoe UI', 10))
subtitle_label.pack()
# Main container
main_container = tk.Frame(self.root, bg=self.colors['bg'])
main_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=(0, 20))
# Create notebook for tabs
self.notebook = ttk.Notebook(main_container)
self.notebook.pack(fill=tk.BOTH, expand=True)
# Hash Generation Tab
self.hash_tab = ttk.Frame(self.notebook)
self.notebook.add(self.hash_tab, text=" Generate Hashes ")
self.setup_hash_tab()
# Verification Tab
self.verify_tab = ttk.Frame(self.notebook)
self.notebook.add(self.verify_tab, text=" Verify Files ")
self.setup_verify_tab()
# Status bar
self.status_bar = tk.Frame(self.root, bg='#E0E0E0', height=25)
self.status_bar.pack(fill=tk.X, side=tk.BOTTOM)
self.status_bar.pack_propagate(False)
self.status_label = tk.Label(self.status_bar,
text="Ready",
bg='#E0E0E0',
fg=self.colors['text'],
font=('Segoe UI', 9))
self.status_label.pack(side=tk.LEFT, padx=10, pady=2)
def setup_hash_tab(self):
"""Setup modern hash generation tab."""
# Scrollable frame
canvas = tk.Canvas(self.hash_tab, bg=self.colors['bg'])
scrollbar = ttk.Scrollbar(self.hash_tab, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas, style='Card.TFrame')
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
# Location selection
location_frame = ttk.LabelFrame(scrollable_frame, text="📁 Select Location",
padding=20, style='Modern.TLabelframe')
location_frame.pack(fill=tk.X, padx=20, pady=10)
self.location_var = tk.StringVar()
location_entry = ttk.Entry(location_frame, textvariable=self.location_var,
font=('Segoe UI', 10), width=50)
location_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
btn_frame = tk.Frame(location_frame, bg='white')
btn_frame.pack(side=tk.RIGHT)
ttk.Button(btn_frame, text="📄 File", command=self.browse_file,
style='Modern.TButton').pack(side=tk.LEFT, padx=2)
ttk.Button(btn_frame, text="📁 Folder", command=self.browse_folder,
style='Modern.TButton').pack(side=tk.LEFT, padx=2)
# Algorithm and settings
settings_frame = ttk.LabelFrame(scrollable_frame, text="⚙️ Settings",
padding=20, style='Modern.TLabelframe')
settings_frame.pack(fill=tk.X, padx=20, pady=10)
# Algorithm selection
algo_frame = tk.Frame(settings_frame, bg='white')
algo_frame.pack(fill=tk.X, pady=(0, 15))
tk.Label(algo_frame, text="Hash Algorithm:", bg='white',
font=('Segoe UI', 10, 'bold'), fg=self.colors['text']).pack(side=tk.LEFT)
self.algorithm_var = tk.StringVar(value='SHA256')
algo_combo = ttk.Combobox(algo_frame, textvariable=self.algorithm_var,
values=list(self.hash_generator.SUPPORTED_ALGORITHMS.keys()),
state='readonly', font=('Segoe UI', 10), width=15)
algo_combo.pack(side=tk.LEFT, padx=(10, 0))
# Performance settings
perf_frame = tk.Frame(settings_frame, bg='white')
perf_frame.pack(fill=tk.X)
tk.Label(perf_frame, text="Threads:", bg='white',
font=('Segoe UI', 10, 'bold'), fg=self.colors['text']).pack(side=tk.LEFT)
self.threads_var = tk.StringVar(value='4')
threads_spin = ttk.Spinbox(perf_frame, from_=1, to=16, width=5,
textvariable=self.threads_var, font=('Segoe UI', 10))
threads_spin.pack(side=tk.LEFT, padx=(10, 20))
# Auto-save option
self.autosave_var = tk.BooleanVar(value=True)
autosave_check = ttk.Checkbutton(perf_frame, text="Auto-save results",
variable=self.autosave_var)
autosave_check.pack(side=tk.LEFT)
# Control buttons
control_frame = ttk.Frame(scrollable_frame, style='Card.TFrame', padding=20)
control_frame.pack(fill=tk.X, padx=20, pady=10)
btn_container = tk.Frame(control_frame, bg='white')
btn_container.pack()
self.generate_btn = ttk.Button(btn_container, text="🔄 Generate Hashes",
command=self.generate_hashes,
style='Primary.TButton')
self.generate_btn.pack(side=tk.LEFT, padx=5)
self.stop_btn = ttk.Button(btn_container, text="⏹️ Stop",
command=self.stop_operation,
style='Error.TButton', state=tk.DISABLED)
self.stop_btn.pack(side=tk.LEFT, padx=5)
self.save_btn = ttk.Button(btn_container, text="💾 Save Results",
command=self.save_results,
style='Success.TButton', state=tk.DISABLED)
self.save_btn.pack(side=tk.LEFT, padx=5)
# Progress
progress_frame = ttk.Frame(scrollable_frame, style='Card.TFrame', padding=20)
progress_frame.pack(fill=tk.X, padx=20, pady=10)
self.progress_var = tk.StringVar(value="Ready to generate hashes")
progress_label = tk.Label(progress_frame, textvariable=self.progress_var,
bg='white', font=('Segoe UI', 10), fg=self.colors['text'])
progress_label.pack(anchor=tk.W, pady=(0, 10))
self.progress_bar = ttk.Progressbar(progress_frame, length=400, mode='determinate',
style='Modern.Horizontal.TProgressbar')
self.progress_bar.pack(fill=tk.X)
# Results
results_frame = ttk.LabelFrame(scrollable_frame, text="📊 Results",
padding=20, style='Modern.TLabelframe')
results_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
self.results_text = scrolledtext.ScrolledText(results_frame, height=12, wrap=tk.WORD,
font=('Consolas', 9), bg='#F8F8F8')
self.results_text.pack(fill=tk.BOTH, expand=True)
# Pack canvas and scrollbar
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
def setup_verify_tab(self):
"""Setup modern verification tab."""
# Scrollable frame
canvas = tk.Canvas(self.verify_tab, bg=self.colors['bg'])
scrollbar = ttk.Scrollbar(self.verify_tab, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas, style='Card.TFrame')
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
# Hash file selection
hash_file_frame = ttk.LabelFrame(scrollable_frame, text="📋 Hash File",
padding=20, style='Modern.TLabelframe')
hash_file_frame.pack(fill=tk.X, padx=20, pady=10)
self.hash_file_var = tk.StringVar()
hash_file_entry = ttk.Entry(hash_file_frame, textvariable=self.hash_file_var,
font=('Segoe UI', 10), width=50)
hash_file_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
ttk.Button(hash_file_frame, text="📂 Browse",
command=self.browse_hash_file, style='Modern.TButton').pack(side=tk.RIGHT)
# Base path selection
base_path_frame = ttk.LabelFrame(scrollable_frame, text="📍 Base Path (Optional)",
padding=20, style='Modern.TLabelframe')
base_path_frame.pack(fill=tk.X, padx=20, pady=10)
self.base_path_var = tk.StringVar()
base_path_entry = ttk.Entry(base_path_frame, textvariable=self.base_path_var,
font=('Segoe UI', 10), width=50)
base_path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
ttk.Button(base_path_frame, text="📂 Browse",
command=self.browse_base_path, style='Modern.TButton').pack(side=tk.RIGHT)
# Settings
verify_settings_frame = ttk.LabelFrame(scrollable_frame, text="⚙️ Verification Settings",
padding=20, style='Modern.TLabelframe')
verify_settings_frame.pack(fill=tk.X, padx=20, pady=10)
self.auto_save_report_var = tk.BooleanVar(value=True)
ttk.Checkbutton(verify_settings_frame, text="Auto-save verification report",
variable=self.auto_save_report_var).pack(anchor=tk.W)
# Control buttons
verify_control_frame = ttk.Frame(scrollable_frame, style='Card.TFrame', padding=20)
verify_control_frame.pack(fill=tk.X, padx=20, pady=10)
verify_btn_container = tk.Frame(verify_control_frame, bg='white')
verify_btn_container.pack()
self.verify_btn = ttk.Button(verify_btn_container, text="🔍 Verify Files",
command=self.verify_files,
style='Primary.TButton')
self.verify_btn.pack(side=tk.LEFT, padx=5)
self.verify_stop_btn = ttk.Button(verify_btn_container, text="⏹️ Stop",
command=self.stop_operation,
style='Error.TButton', state=tk.DISABLED)
self.verify_stop_btn.pack(side=tk.LEFT, padx=5)
self.save_report_btn = ttk.Button(verify_btn_container, text="📄 Save Report",
command=self.save_verification_report,
style='Success.TButton', state=tk.DISABLED)
self.save_report_btn.pack(side=tk.LEFT, padx=5)
# Progress
verify_progress_frame = ttk.Frame(scrollable_frame, style='Card.TFrame', padding=20)
verify_progress_frame.pack(fill=tk.X, padx=20, pady=10)
self.verify_progress_var = tk.StringVar(value="Ready to verify files")
verify_progress_label = tk.Label(verify_progress_frame, textvariable=self.verify_progress_var,
bg='white', font=('Segoe UI', 10), fg=self.colors['text'])
verify_progress_label.pack(anchor=tk.W, pady=(0, 10))
self.verify_progress_bar = ttk.Progressbar(verify_progress_frame, length=400, mode='determinate',
style='Modern.Horizontal.TProgressbar')
self.verify_progress_bar.pack(fill=tk.X)
# Results
verify_results_frame = ttk.LabelFrame(scrollable_frame, text="🔍 Verification Results",
padding=20, style='Modern.TLabelframe')
verify_results_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
self.verify_results_text = scrolledtext.ScrolledText(verify_results_frame, height=12,
wrap=tk.WORD, font=('Consolas', 9),
bg='#F8F8F8')
self.verify_results_text.pack(fill=tk.BOTH, expand=True)
# Store verification results
self.verification_results = {}
self.corrupted_files = []
self.verification_errors = []
# Pack canvas and scrollbar
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
def browse_file(self):
"""Browse for a single file."""
filename = filedialog.askopenfilename(
title="Select File to Hash",
filetypes=[("All Files", "*.*")]
)
if filename:
self.location_var.set(filename)
self.update_status(f"Selected file: {os.path.basename(filename)}")
def browse_folder(self):
"""Browse for a folder."""
foldername = filedialog.askdirectory(title="Select Folder to Scan")
if foldername:
self.location_var.set(foldername)
self.update_status(f"Selected folder: {os.path.basename(foldername)}")
def browse_hash_file(self):
"""Browse for hash file."""
filename = filedialog.askopenfilename(
title="Select Hash File",
filetypes=[("JSON Files", "*.json"), ("All Files", "*.*")]
)
if filename:
self.hash_file_var.set(filename)
self.update_status(f"Selected hash file: {os.path.basename(filename)}")
def browse_base_path(self):
"""Browse for base path."""
foldername = filedialog.askdirectory(title="Select Base Path")
if foldername:
self.base_path_var.set(foldername)
self.update_status(f"Selected base path: {os.path.basename(foldername)}")
def update_status(self, message):
"""Update status bar."""
self.status_label.config(text=message)
self.root.update_idletasks()
def update_progress(self, current, total, current_file):
"""Update progress bar and status."""
progress = (current / total) * 100 if total > 0 else 0
self.progress_bar['value'] = progress
filename = os.path.basename(current_file)
self.progress_var.set(f"Processing: {filename} ({current}/{total})")
self.update_status(f"Generating hashes... {current}/{total} files processed")
self.root.update_idletasks()
def update_verify_progress(self, current, total, current_file):
"""Update verification progress bar and status."""
progress = (current / total) * 100 if total > 0 else 0
self.verify_progress_bar['value'] = progress
filename = os.path.basename(current_file)
self.verify_progress_var.set(f"Verifying: {filename} ({current}/{total})")
self.update_status(f"Verifying files... {current}/{total} files checked")
self.root.update_idletasks()
def generate_hashes(self):
"""Generate hashes for selected location."""
location = self.location_var.get().strip()
if not location or not os.path.exists(location):
messagebox.showerror("❌ Error", "Please select a valid file or folder.")
return
algorithm = self.algorithm_var.get()
max_workers = int(self.threads_var.get())
# Disable controls
self.generate_btn.config(state=tk.DISABLED)
self.stop_btn.config(state=tk.NORMAL)
self.save_btn.config(state=tk.DISABLED)
# Clear results
self.results_text.delete(1.0, tk.END)
self.progress_bar['value'] = 0
# Reset stop event
self.hash_generator.reset_stop_event()
def hash_thread():
try:
self.progress_var.set("Initializing hash generation...")
self.update_status("Starting hash generation...")
self.root.update_idletasks()
# Generate hashes
self.hash_results, self.error_files = self.hash_generator.scan_location(
location, algorithm, self.update_progress, max_workers
)
# Auto-save if enabled
if self.autosave_var.get() and (self.hash_results or self.error_files):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
auto_filename = f"hash_results_{timestamp}.json"
self.hash_generator.save_hashes(
self.hash_results, self.error_files, auto_filename,
algorithm, location
)
self.root.after(0, lambda: self.update_status(f"Results auto-saved to {auto_filename}"))
# Display results
self.root.after(0, self.display_hash_results)
except Exception as e:
self.root.after(0, lambda: messagebox.showerror("❌ Error", f"Hash generation failed: {str(e)}"))
finally:
self.root.after(0, self.hash_generation_complete)
# Start thread
self.current_operation = threading.Thread(target=hash_thread)
self.current_operation.start()
def display_hash_results(self):
"""Display hash generation results with better formatting."""
self.results_text.delete(1.0, tk.END)
if not self.hash_results and not self.error_files:
self.results_text.insert(tk.END, "❌ No files processed or operation was cancelled.\n")
return
# Header
self.results_text.insert(tk.END, "=" * 80 + "\n")
self.results_text.insert(tk.END, f"📊 HASH GENERATION RESULTS\n")
self.results_text.insert(tk.END, "=" * 80 + "\n\n")
# Summary
self.results_text.insert(tk.END, f"🔧 Algorithm: {self.algorithm_var.get()}\n")
self.results_text.insert(tk.END, f"📁 Location: {self.location_var.get()}\n")
self.results_text.insert(tk.END, f"✅ Files processed: {len(self.hash_results)}\n")
self.results_text.insert(tk.END, f"❌ Files with errors: {len(self.error_files)}\n")
self.results_text.insert(tk.END, f"🕒 Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
# Successful hashes
if self.hash_results:
self.results_text.insert(tk.END, f"✅ SUCCESSFUL HASHES ({len(self.hash_results)} files)\n")
self.results_text.insert(tk.END, "-" * 50 + "\n")
for i, (file_path, hash_value) in enumerate(self.hash_results.items(), 1):
filename = os.path.basename(file_path)
self.results_text.insert(tk.END, f"{i:3d}. {filename}\n")
self.results_text.insert(tk.END, f" Path: {file_path}\n")
self.results_text.insert(tk.END, f" Hash: {hash_value}\n\n")
# Error files
if self.error_files:
self.results_text.insert(tk.END, f"❌ FILES WITH ERRORS ({len(self.error_files)} files)\n")
self.results_text.insert(tk.END, "-" * 50 + "\n")
for i, error in enumerate(self.error_files, 1):
self.results_text.insert(tk.END, f"{i:3d}. {error}\n")
self.results_text.see(1.0)
self.save_btn.config(state=tk.NORMAL)
def hash_generation_complete(self):
"""Re-enable controls after hash generation."""
self.generate_btn.config(state=tk.NORMAL)
self.stop_btn.config(state=tk.DISABLED)
self.progress_var.set("Hash generation complete")
self.update_status("Ready")
self.current_operation = None
def save_results(self):
"""Save hash results to file."""
if not self.hash_results and not self.error_files:
messagebox.showwarning("⚠️ Warning", "No results to save.")
return
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
default_name = f"hash_results_{timestamp}.json"
filename = filedialog.asksaveasfilename(
title="Save Hash Results",
defaultextension=".json",
initialvalue=default_name,
filetypes=[("JSON Files", "*.json"), ("All Files", "*.*")]
)
if filename:
if self.hash_generator.save_hashes(
self.hash_results, self.error_files, filename,
self.algorithm_var.get(), self.location_var.get()
):
messagebox.showinfo("✅ Success", f"Hash results saved to:\n{filename}")
if self.error_files:
error_file = filename.replace('.json', '_errors.txt')
messagebox.showinfo("📄 Additional File", f"Error report saved to:\n{error_file}")
self.update_status(f"Results saved to {os.path.basename(filename)}")
else:
messagebox.showerror("❌ Error", "Failed to save hash results.")
def verify_files(self):
"""Verify files against saved hashes."""
hash_file = self.hash_file_var.get().strip()
if not hash_file or not os.path.exists(hash_file):
messagebox.showerror("❌ Error", "Please select a valid hash file.")
return
base_path = self.base_path_var.get().strip() or None
# Disable controls
self.verify_btn.config(state=tk.DISABLED)
self.verify_stop_btn.config(state=tk.NORMAL)
self.save_report_btn.config(state=tk.DISABLED)
# Clear results
self.verify_results_text.delete(1.0, tk.END)
self.verify_progress_bar['value'] = 0
# Reset stop event
self.hash_generator.reset_stop_event()
def verify_thread():
try:
self.verify_progress_var.set("Initializing verification...")
self.update_status("Starting file verification...")
self.root.update_idletasks()
# Verify files
self.verification_results, self.corrupted_files, self.verification_errors = \
self.hash_generator.verify_integrity(hash_file, base_path, self.update_verify_progress)
# Auto-save report if enabled
if self.auto_save_report_var.get() and self.verification_results:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
auto_filename = f"verification_report_{timestamp}.json"
self.hash_generator.save_verification_report(
self.verification_results, self.corrupted_files,
self.verification_errors, auto_filename, hash_file
)
self.root.after(0, lambda: self.update_status(f"Report auto-saved to {auto_filename}"))
# Display results
self.root.after(0, self.display_verify_results)
except Exception as e:
self.root.after(0, lambda: messagebox.showerror("❌ Error", f"Verification failed: {str(e)}"))
finally:
self.root.after(0, self.verification_complete)
# Start thread
self.current_operation = threading.Thread(target=verify_thread)
self.current_operation.start()