-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfilecrypt.py
More file actions
2131 lines (1754 loc) · 71.3 KB
/
filecrypt.py
File metadata and controls
2131 lines (1754 loc) · 71.3 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
"""
Filecrypt encrypts/decrypts files in the current folder
using the AES algorithm via the Fernet implementation.
To do this, simply :
- Place this script in the folder containing the file(s)
to be encrypted or decrypted.
- Go to this folder from the terminal.
- Call the script: 'python filecrypt.py' followed by the
desired command.
Example : 'python filecrypt.py encrypt image.jpg -ow'
All information and examples on :
https://github.com/Kartmaan/filecrypt
Or :
'python filecrypt.py --help'
Author : Kartmaan
Date : 2026-03-08
Version : 1.2.1
"""
# ===================================================================
# BUILT-IN MODULES
# ===================================================================
import argparse
import base64
import errno
import getpass
from datetime import datetime as dt
from os import chmod, remove, rmdir, urandom, walk
from os.path import abspath, basename, dirname, exists, getsize
from os.path import isdir, isfile, join, relpath, realpath
import secrets
from shutil import copyfile, rmtree
import stat
from string import ascii_letters, ascii_lowercase
from string import ascii_uppercase, digits, punctuation
import subprocess
import sys
from typing import Union
from zipfile import ZipFile, BadZipFile, ZIP_DEFLATED
# ===================================================================
# CONSTANTS
# ===================================================================
USER_OS = sys.platform
SUPPORTED_OS = ["win32", "linux", "darwin"]
SAFE_MODE = False
SCRIPT_PATH = abspath(sys.argv[0])
SCRIPT_DIR = dirname(SCRIPT_PATH)
SCRIPT_NAME = basename(SCRIPT_PATH)
REQUIREMENTS = ["cryptography", "pyperclip", "python-dateutil"]
FILEKEY_EXT = ".key"
# ===================================================================
# OUTPUT FORMATTING
# ===================================================================
# A small set of helpers that give the terminal output a consistent
# visual vocabulary. Every print() in the script should go through
# one of these rather than calling print() directly.
#
# _fmt_header(text) — opening line of an operation
# _fmt_step(text) — progress line inside an operation
# _fmt_ok(text) — closing line on success
# _fmt_info(text) — supplementary note after a result
# _fmt_err(text) — error message (standalone, no open block)
# _fmt_warn(text) — warning / caution block
# _fmt_result(...) — bordered info box (e.g. timestamp output)
# _fmt_ask(text) — prompt label (returns the string, no newline)
def _fmt_header(text: str) -> None:
print(f"\n ┌─ {text}")
def _fmt_step(text: str) -> None:
print(f" │ {text}")
def _fmt_ok(text: str = "Operation completed successfully") -> None:
print(f" └─ ✓ {text}\n")
def _fmt_info(text: str) -> None:
print(f" {text}")
def _fmt_err(text: str) -> None:
print(f"\n ✗ {text}\n")
def _fmt_warn(title: str, body: str = "") -> None:
print(f"\n ⚠ {title}")
if body:
for line in body.splitlines():
print(f" {line}")
print()
def _fmt_result(lines_dict: dict, title: str = "") -> None:
"""Prints a bordered info box.
lines_dict: OrderedDict-style {label: value} pairs.
"""
if title:
print(f"\n ╌╌ {title} ╌╌")
else:
print(f"\n ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌")
label_width = max(len(k) for k in lines_dict) if lines_dict else 0
for label, value in lines_dict.items():
print(f" │ {label:<{label_width}} {value}")
print(f" ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌\n")
def _fmt_ask(text: str) -> str:
"""Returns a consistently indented prompt string for use with
input() or getpass()."""
return f" │ {text}"
# ===================================================================
# NON-BUILT-IN MODULES
# ===================================================================
def install_from_requirements():
"""
Installs modules listed in the 'REQUIREMENTS' list with pip.
"""
for package in REQUIREMENTS:
try:
# Tries to install the package with pip
_fmt_step(f"Installing {package}...")
subprocess.check_call([sys.executable, "-m",
"pip", "install", package])
_fmt_step(f"{package} installed.")
except subprocess.CalledProcessError:
_fmt_err(f"Unable to install {package}. Check your connection.")
raise
except Exception as e:
_fmt_err(f"An unexpected error has occurred : {e}.")
raise
# As these modules are not built-in, we insert them in a
# try...except block to suggest that the user install
# them if they are not present in his environment.
try :
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from dateutil.relativedelta import relativedelta
import pyperclip
except ImportError:
choice = None
while choice != "y" and choice != "n":
_fmt_warn("Missing modules",
f"The following modules are not installed: {REQUIREMENTS}")
choice = input("Do you want to install them ? (y/n): ")
choice = choice.lower()
if choice == "y":
install_from_requirements()
sys.exit(0)
elif choice == "n":
_fmt_info("Please install the missing modules manually.")
sys.exit(1)
else:
_fmt_err("Invalid input.")
continue
# ===================================================================
# SAFETY CHECKS
# ===================================================================
def safety_check(func):
"""Decorator : prevents a function from operating in
SAFE_MODE.
The decorator is attached to all functions able of
modifying/deleting files/folders.
Args:
func: The decorated function.
Returns:
func: SAFE_MODE OFF -> The function is called
wrap: SAFE_MODE ON -> The function is muted
"""
txt=f"This functionality ({func.__name__}) isn't available in safe mode."
def wrap(*args, **kwargs):
if SAFE_MODE:
_fmt_warn("SAFE MODE", txt)
sys.exit(1)
else:
return func(*args, **kwargs)
return wrap
def in_danger_zone(path: str) -> bool:
"""Determines whether a path corresponds to a
sensitive area of the system.
Args:
path (str): Path to check.
Returns:
bool: True if the path corresponds to a sensitive
area. False otherwise.
"""
# For each system, all paths STARTING with these are
# considered sensitive
danger_roots = {
"win32": ["c:\\windows"],
"linux": ["/bin", "/sbin", "/usr", "/etc", "/var"],
"darwin": ["/bin", "/sbin", "/usr", "/etc", "/var",
"/System"]}
# For each system, all paths EQUAL to these are
# considered sensitive
danger_path = {
"win32": ["c:\\"],
"linux": ["/"],
"darwin": ["/"]}
# Resolve symlinks and normalize the path, then convert to lowercase
resolved_path = realpath(path).lower()
for root_path in danger_roots[USER_OS]:
if resolved_path.startswith(root_path):
return True
for root_path in danger_path[USER_OS]:
if resolved_path == root_path:
return True
return False
def in_current_folder(path: str) -> bool:
"""Checks if the path or file name inserted by the
user is in the script's current folder.
Functions that modify file contents or delete
them, expect a target path as argument, and it's
important to ensure that these functions CAN'T reach
sensitive areas of the system.
The script goes into SAFE_MODE when it is in a
sensitive area of the system, which prevents the
script's modifier functions from being called.
However, to ensure that these zones cannot be reached
when the script is not in SAFE_MODE, by, for example,
entering a sensitive path as an argument, these are
checked to ensure that they are actually in the
script's current folder.
Args:
path (str): Path to check.
Returns:
bool: True if the path is in the current folder.
False otherwise.
"""
# Resolve symlinks and normalize the path, then convert to lowercase
real_target_path = realpath(path).lower()
real_script_dir = realpath(SCRIPT_DIR).lower()
if real_target_path.startswith(real_script_dir):
return True
else:
return False
def handle_remove_readonly(func: callable, path: str, exc: tuple[any, Exception, any]) -> None:
"""Handles errors in deleting read-only files or folders, particularly under Windows.
This function is designed to be used as a callback via the 'onerror' parameter of shutil.rmtree().
It intercepts deletion failures due to insufficient permissions (EACCES), modifies the element's
attributes to allow writing, and then retries the operation.
Args:
func: The function that failed.
path: The absolute or relative path of the file or folder to be deleted.
exc: A tuple containing information about the exception thrown (type, value, traceback),
as returned by sys.exc_info().
Raises:
Exception: Re-throws the original exception if the error is not related to an access
problem (EACCES) or if the rights modification fails.
"""
excvalue = exc[1]
if func in (rmdir, remove) and excvalue.errno == errno.EACCES:
chmod(path, stat.S_IWRITE) # We make the file/folder writable
func(path) # We'll try the deletion again.
else:
raise
# ===================================================================
# INITIAL CHECKS
# ===================================================================
if USER_OS not in SUPPORTED_OS:
_fmt_err(f"This OS ({USER_OS}) isn't supported. Supported: {SUPPORTED_OS}")
sys.exit(1)
# If the script is in a sensitive area of the system,
# SAFE_MODE is activated.
if in_danger_zone(SCRIPT_PATH):
SAFE_MODE = True
_fmt_warn("SAFE MODE",
"The script is located in a critical area of the system.\n"
"File-modifying operations are disabled.")
# ===================================================================
# INPUT CONTROL FUNCTIONS
# ===================================================================
def valid_b64_urlsafe(b64_code: Union[str, bytes]) -> bool:
"""Checks if the entry is a valid base64 urlsafe code.
Fernet manipulates keys in the form of base64 urlsafe
code, so we'll make sure the input respects this format.
Args:
b64_code (Union[str, bytes]): Entry to check
Returns:
bool: Valid base64 urlsafe (True) or not (False)
"""
try:
base64.urlsafe_b64decode(b64_code)
return True
except Exception:
return False
def valid_filename(file_name: str) -> bool:
"""Checks if a file name is valid including by checking
if all its characters are in a whitelist.
Args:
file_name (str): Name of the file to be checked
Returns:
bool: Valid file name (True) or not (False)
"""
# Whitelist composed of letters, numbers and the
# underscore symbol
symbols = ['_']
letters_digits = list(ascii_letters + digits)
whitelist = symbols + letters_digits
# Not a str (unlikely in the context of this script,
# but who knows?)
if not isinstance(file_name, str):
_fmt_err("File name must be a str.")
return False
# The string is too long
if len(file_name) > 255:
_fmt_err("File name is too long (must contain less than"
"than 256 characters).")
return False
# Iteration to search for a character not in the
# whitelist
for char in file_name:
if char not in whitelist:
_fmt_err("Invalid char in file name.")
return False
# Seems ok
return True
def valid_filekey_name(filekey: str, create: bool = False) -> bool:
"""Checks the validity of a filekey name.
The definition of a valid filekey name depends on
whether the filekey is supposed to be present in the
current folder or created by the user.
Args:
filekey (str): Filekey path
create (bool): Is the filekey supposed to be
created or not (i.e. found in the current folder) ?
Default to False. (optional)
Returns:
bool: Valid filekey name (True) or not (False)
"""
if not isinstance(filekey, str):
_fmt_err(f"Wrong type, must be a str ({type(filekey)}"
" given.)")
return False
# - The filekey will be recovered -
# We are looking for a filekey that is supposed to be
# already present in the current folder. We make sure
# the file exists and has the right extension
if not create:
if not exists(filekey):
_fmt_err(f"{filekey} not found.")
return False
if not filekey.endswith(FILEKEY_EXT):
_fmt_err(f"Filekey must be '{FILEKEY_EXT}'.")
return False
# - The filekey will be created -
# We make sure no file with the same name exists
else:
if not valid_filename(filekey):
return False
if exists(filekey + FILEKEY_EXT):
_fmt_err(f"{filekey} already exists.")
return False
return True
def valid_filekey_key(filekey: str) -> bool:
"""Checks whether the key present in a filekey is valid.
A valid Fernet key must be exactly 32 url-safe base64-encoded
bytes. Checking only that the content is valid base64 is not
sufficient: a string can be decodable yet produce a byte sequence
of the wrong length, causing Fernet() to raise a silent ValueError.
Args:
filekey (str): Given filekey
Returns:
bool: Valid key (True) or not (False).
"""
with open(filekey, "r") as f:
content = f.read().strip()
# Step 1 — must be valid urlsafe base64
if not valid_b64_urlsafe(content):
_fmt_err("Invalid key format: not a valid base64 urlsafe string.")
return False
# Step 2 — decoded bytes must be exactly 32 (Fernet requirement)
import base64 as _b64
decoded = _b64.urlsafe_b64decode(content)
if len(decoded) != 32:
_fmt_err(f"Invalid key length: expected 32 bytes, got {len(decoded)}.")
return False
return True
def valid_filekey(filekey: str) -> bool:
"""Checks the validity of a filekey's name as well as
its contents
Args:
filekey (str): Filekey name (with extension)
Returns:
bool: Valid (True) or not (False)
"""
if valid_filekey_name(filekey) and valid_filekey_key(filekey):
return True
else:
return False
def valid_password(psw: str) -> bool:
"""Checks the validity of a password.
Args:
psw (str): The given password
Returns:
bool: Valid or not
"""
MIN_LENGTH = 5
blacklist = [' ']
if not isinstance(psw, str):
_fmt_err(f"psw must be a str type, {type(psw)} given.")
return False
if len(psw) < MIN_LENGTH:
_fmt_err(f"Password must be at least {MIN_LENGTH} characters long.")
return False
for char in psw:
if char in blacklist:
return False
return True
def get_confidential_input(prompt: str) -> str:
"""Gets confidential input from the user without echoing to the terminal.
This function is a wrapper around `getpass.getpass()`, providing a
standard way to prompt the user for sensitive information like passwords.
The input is not displayed on the screen as the user types.
Args:
prompt: The message to display to the user before input.
Returns:
str: The user's input.
"""
return getpass.getpass(prompt)
# ===================================================================
# FEATURE FUNCTIONS
# ===================================================================
def _clean_linux_native() -> bool:
"""Attempts to clear the clipboard on Linux using native
tools (xclip, xsel, wl-clipboard), without requiring pyperclip.
Tries each tool silently via subprocess. Stops and returns
True as soon as one succeeds.
Returns:
bool: True if a native tool successfully cleared the
clipboard, False if none were available.
"""
# Each entry: (command, description)
# We pipe an empty string into each tool to clear the clipboard.
native_commands = [
["xclip", "-selection", "clipboard"], # X11
["xsel", "--clipboard", "--clear"], # X11
["wl-copy", "--clear"], # Wayland
]
for cmd in native_commands:
try:
result = subprocess.run(
cmd,
input=b"",
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
if result.returncode == 0:
return True
except FileNotFoundError:
# Tool not installed, try the next one
continue
return False
def clean():
"""Clears confidential data on the clipboard.
On all platforms, pyperclip is tried first. On Linux, if
pyperclip raises PyperclipException (no copy/paste mechanism
found), native clipboard tools are attempted as a fallback
(xclip, xsel, wl-clipboard) — without requiring any
installation. If none are available either, the user is
informed of the situation and of the available options.
"""
try:
pyperclip.copy("")
_fmt_ok("Clipboard erased.")
except pyperclip.PyperclipException:
if USER_OS == "linux":
if _clean_linux_native():
_fmt_ok("Clipboard erased.")
else:
_clipboard_no_mechanism_msg()
_fmt_info("Alternatively, clear it manually by copying any innocuous text.")
else:
raise
def _copy_linux_native(text: str) -> bool:
"""Attempts to copy text to the clipboard on Linux using native
tools (xclip, xsel, wl-clipboard), without requiring pyperclip.
Mirrors _clean_linux_native() but pipes the given text instead
of an empty string, covering both X11 and Wayland environments.
Args:
text (str): The text to copy to the clipboard.
Returns:
bool: True if a native tool successfully copied the text,
False if none were available.
"""
native_commands = [
["xclip", "-selection", "clipboard"], # X11
["xsel", "--clipboard", "--input"], # X11
["wl-copy"], # Wayland
]
for cmd in native_commands:
try:
result = subprocess.run(
cmd,
input=text.encode(),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
if result.returncode == 0:
return True
except FileNotFoundError:
# Tool not installed, try the next one
continue
return False
def _clipboard_no_mechanism_msg() -> None:
"""Prints a standardised message when no clipboard mechanism
is available on the current Linux system.
Factored out to keep copy_filekey() and clean() DRY.
"""
_fmt_warn(
"No clipboard mechanism found.",
"Install one of the following tools:\n"
" X11 : sudo apt-get install xclip\n"
" sudo apt-get install xsel\n"
" Wayland : sudo apt-get install wl-clipboard"
)
def copy_filekey(filekey: str):
"""Copies the Base64 key stored in a filekey to the clipboard.
On all platforms, pyperclip is tried first. On Linux, if
pyperclip raises PyperclipException (no copy/paste mechanism
found), native clipboard tools are attempted as a fallback
(xclip, xsel, wl-clipboard) — without requiring any
installation. If none are available either, the user is
informed of the situation and of the available options.
Args:
filekey (str): Filekey name (with extension).
Error:
Invalid filekey : sys.exit(1)
No clipboard mechanism available : informs the user
"""
key = read_filekey(filekey, return_value=True)
if key is None:
sys.exit(1)
try:
pyperclip.copy(key)
_fmt_ok("Key copied to clipboard.")
_fmt_info("Don't forget to clean the clipboard after use ('clean' command).")
except pyperclip.PyperclipException:
if USER_OS == "linux":
if _copy_linux_native(key):
_fmt_ok("Key copied to clipboard.")
_fmt_info("Don't forget to clean the clipboard after use ('clean' command).")
else:
_clipboard_no_mechanism_msg()
else:
raise
def read_filekey(filekey: str, return_value: bool = False) -> str | None:
"""Displays or returns the Base64 key of a filekey.
Args:
filekey (str): Filekey with extension
return_value (bool): If True, the 'content'
variable is returned, otherwise it's simply
displayed. Default to False. (optional)
Error:
Invalid filekey : sys.exit(1)
Return:
str : The b64 key
"""
if valid_filekey(filekey):
with open(filekey, "r") as f:
content = f.read()
if not return_value:
_fmt_info(content)
else:
return content
else:
sys.exit(1)
@safety_check
def create_filekey(file_name: str, key: str):
"""Creates a filekey based on a base64 key.
If the key is valid, this filekey can be used to
encrypt and decrypt data.
Args:
file_name (str): Desired name for filekey without extension
key (str): Secret key (base64 urlsafe)
Error:
Invalid file name: sys.exit(1)
Invalid filekey name: sys.exit(1)
Invalid key: sys.exit(1)
"""
if not valid_filename(file_name):
sys.exit(1)
if not valid_filekey_name(file_name, create = True):
sys.exit(1)
# No spaces
key = key.replace(' ', '')
key_bytes = bytes(key, 'ascii')
if valid_b64_urlsafe(key_bytes):
with open(file_name + FILEKEY_EXT, 'wb') as f:
f.write(key_bytes)
_fmt_ok(f"{file_name + FILEKEY_EXT} created in the current folder.")
else:
_fmt_err("Invalid key, must be base64 urlsafe.")
sys.exit(1)
@safety_check
def secure_delete(filename: str, encryption_passes: int = 2,
shuffle: bool = False, silent_mode: bool = False):
"""
Securely deletes files/folders from the current folder.
Before deletion, files are blindly encrypted
several times (without the key being communicated)
with a new random key for each pass. Finally, the
file size is truncated to coincide with the original
size.
Optionally, the file bytes can be randomly shuffled
just after truncation by activating the option
'--shuffle' / '-s'.
Note about encryption passes: The file size can
temporarily increase significantly with each
encryption pass. Even if the file returns to its
initial size after the truncation phase, setting
the number of passes to 2 seems a more than
acceptable compromise, particularly for large files.
Note about the shuffle option: The operation can
be long for large files (approx. 2 min on a standard
PC for a 100MB file).
Args:
filename (str): The file name to delete.
encryption_passes (int): The number of encryption
passes. Default to 2.
shuffle (bool): Random file bytes shuffling
before deletion. Default to False.
silent_mode (bool): Minimum prints
Error:
Invalid filename arg: sys.exit(1)
Invalid encryption_passes arg: sys.exit(1)
File not found: sys.exit(1)
Current script as filename arg: sys.exit(1)
Error during encryption: raise Exception
Error during shuffle: OSError
"""
is_filekey = False
is_folder = False
if not isinstance(filename, str):
_fmt_err("filename must be a str.")
sys.exit(1)
elif not isinstance(encryption_passes, int) or encryption_passes < 0:
_fmt_err("Invalid 'encryption_passes' arg. Must be an integer >= 0.")
sys.exit(1)
elif not in_current_folder(filename):
_fmt_err(f"{filename} is not in the current folder.")
sys.exit(1)
# Prevents script from killing itself
elif filename == SCRIPT_PATH or filename == SCRIPT_NAME:
_fmt_err("I'm sorry user, I'm afraid I can't do that. Deleting myself is not in my programming.")
sys.exit(1)
# Early folder detection (before confirmation)
if isdir(filename):
is_folder = True
# The file to be deleted is a filekey
elif filename.endswith(FILEKEY_EXT):
is_filekey = True
if not silent_mode:
# User confirmation — single prompt, adapted to the target type
choice = None
while choice != "y" and choice != "n":
if is_folder:
# Count all files in the folder (recursively)
file_count = sum(len(files) for _, _, files in walk(filename))
_fmt_warn(
f"You are about to irreversibly delete the folder '{filename}'.",
f"Location : {abspath(filename)}\n"
f"Files : {file_count}")
elif is_filekey:
_fmt_warn(
f"You are about to irreversibly delete the filekey '{filename}'.",
"If it's still needed for decryption, note its key first ('read' command).\n"
f"Location : {abspath(filename)}")
else:
original_file_size = getsize(filename)
_fmt_warn(
f"You are about to irreversibly delete '{filename}'.",
f"Location : {abspath(filename)}\n"
f"Size : {round(original_file_size/1024, 3)} ko")
choice = input(_fmt_ask("Confirm? (y/n): "))
choice = choice.lower()
if choice == "y":
pass
elif choice == "n":
_fmt_info("Cancelled.")
sys.exit(0)
else:
_fmt_err("Invalid input.")
continue
# Get original file size (only needed for files, after confirmation)
if not is_folder:
original_file_size = getsize(filename)
# TARGET IS A FOLDER
if is_folder:
if not silent_mode:
_fmt_header(f"Deleting folder · {filename}")
# Securely delete each file inside the folder recursively
for root, dirs, files in walk(filename):
for file in files:
file_path = join(root, file)
secure_delete(file_path, encryption_passes, shuffle, silent_mode=True)
# Once empty, remove the folder tree
try:
rmtree(filename, onerror=handle_remove_readonly)
if not silent_mode:
_fmt_ok(f"Folder '{filename}' deleted.")
except Exception as e:
_fmt_err(f"Error removing folder '{filename}': {e}")
return # End of function for folder case
if not silent_mode:
if encryption_passes > 0:
_fmt_step("Overwriting...")
# Encryption passes
for i in range(encryption_passes):
# Generate a random key
key = Fernet.generate_key()
# Generate a random salt
salt = urandom(16)
# Derive the key using PBKDF2HMAC
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=480000,
)
derived_key = kdf.derive(key)
encoded_key = base64.urlsafe_b64encode(derived_key)
f = Fernet(encoded_key)
try:
with open(filename, "rb") as file:
original_data = file.read()
encrypted_data = f.encrypt(original_data)
with open(filename, "wb") as file:
file.write(encrypted_data)
if encryption_passes > 1 and not silent_mode:
_fmt_step(f"Pass {i + 1}/{encryption_passes} completed.")
except Exception as e:
_fmt_err(f"Error during encryption pass {i + 1}: {e}.")
raise
# File truncation and shuffle
# File is truncated and bytes are randomly shuffled if
# 'shuffle' is True.
try:
with open(filename, "r+b") as f:
# Truncates the file to its original size
if not silent_mode:
_fmt_step("Resizing...")
f.truncate(original_file_size)
if shuffle:
if not silent_mode:
_fmt_step("Shuffling bytes...")
# Bytes type is immutable, so we transform
# it into a bytearray, which is a mutable
# sequence.
bytes_array = bytearray(f.read())
# Inplace bytearray shuffle
# The SystemRandom class uses the operating
# system's entropy to make a crypto secure
# shuffle.
secrets.SystemRandom().shuffle(bytes_array)
# returns the cursor to the beginning of the
# file before writing the shuffled bytes
f.seek(0)
# Writing shuffled bytes
f.write(bytes_array)
except OSError:
raise
remove(filename) # Delete the file after encryption
if not silent_mode:
_fmt_ok(f"'{filename}' deleted.")
@safety_check
def zip_files(targets: list, delete: bool = False):
"""
Compresses files or folders into a ZIP archive.
Args:
zip_files (list): List of targets
delete (bool): Delete the original files after creating the zip archive.
"""
# Preliminary check of all files
for target in targets:
if not in_current_folder(target):
_fmt_err(f"{target} is not in the current folder.")
sys.exit(1)
if target == SCRIPT_PATH or target == SCRIPT_NAME:
_fmt_err("I'm sorry user, I'm afraid I can't do that. Deleting myself is not in my programming.")
sys.exit(1)
zip_filename = "archive.zip"
# If archive.zip already exist, we request a new name
if exists(zip_filename):
_fmt_warn(f"An archive named '{zip_filename}' already exists.")
while True:
# Naming without extension
custom_name = input("Enter a name for the archive (without extension): ").strip()
if not custom_name:
_fmt_err("Name cannot be empty.")
continue
zip_filename = custom_name + ".zip"
# We're also checking if this new name is available.
if exists(zip_filename):
_fmt_err(f"'{zip_filename}' also exists. Please choose another name.")
else:
break
# User confirmation for deletion
if delete:
_fmt_warn(
"The following targets will be deleted after compression:",
"\n".join(f" - {t}" for t in targets))
choice = input(_fmt_ask("Confirm? (y/n): ")).lower()
if choice != 'y':
_fmt_info("Cancelled.")
sys.exit(0)
_fmt_header(f"Zipping · {', '.join(targets)}")
with ZipFile(zip_filename, 'w', ZIP_DEFLATED) as zipf:
for target_to_zip in targets:
# Targer is a folder
if isdir(target_to_zip):
for root, dirs, files in walk(target_to_zip):
for file in files:
file_path = join(root, file)
arch_name = join(basename(target_to_zip), relpath(file_path, start=target_to_zip))
zipf.write(file_path, arcname=arch_name)
_fmt_step(f"Added: {file_path}")
if delete:
# Recursive deletion logic
total_files = sum([len(files) for r, d, files in walk(target_to_zip)])
_fmt_step(f"Deleting source files in {target_to_zip}...")
deleted_files = 0
for root, dirs, files in walk(target_to_zip):
for file in files:
secure_delete(join(root, file), silent_mode=True)
deleted_files += 1
_fmt_step(f"Deleted {deleted_files}/{total_files}")
# Once the files are deleted, the empty folder is deleted.
# We use `onerror` to handle stubborn cases in Windows.
try:
rmtree(target_to_zip, ignore_errors=False, onerror=handle_remove_readonly)
_fmt_step(f"Folder {target_to_zip} removed.")
except Exception as e:
_fmt_err(f"Could not remove folder {target_to_zip}: {e}")
# Target is a file
elif isfile(target_to_zip):