cryptshield 1.0.0__tar.gz → 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: cryptshield
3
- Version: 1.0.0
3
+ Version: 1.0.1
4
4
  Summary: Secure Encryption and Deletion Application
5
5
  Author-email: Wilmer Martinez <info@wilmermartinez.dev>
6
6
  License: MIT License
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cryptshield"
7
- version = "1.0.0"
7
+ version = "1.0.1"
8
8
  authors = [
9
9
  { name = "Wilmer Martinez", email = "info@wilmermartinez.dev" }
10
10
  ]
@@ -60,5 +60,6 @@ Release = "https://github.com/wilmerm/cryptshield/releases"
60
60
 
61
61
  [tool.setuptools.packages.find]
62
62
  where = ["src"]
63
+ include = ["cryptshield"]
63
64
 
64
65
 
@@ -0,0 +1,16 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="cryptshield",
5
+ version="1.0.1",
6
+ packages=find_packages(where="src"),
7
+ package_dir={"": "src"},
8
+ install_requires=[
9
+ "cryptography",
10
+ ],
11
+ entry_points={
12
+ "console_scripts": [
13
+ "cryptshield=cryptshield.cryptshield:main",
14
+ ]
15
+ },
16
+ )
@@ -0,0 +1,4 @@
1
+ __version__ = "1.0.1"
2
+
3
+
4
+ from .cryptshield import *
@@ -0,0 +1,477 @@
1
+ import logging
2
+ import sys
3
+ import os
4
+ import subprocess
5
+ import hashlib
6
+ import base64
7
+ import glob
8
+ from typing import List
9
+
10
+ from cryptography.fernet import Fernet, InvalidToken
11
+
12
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src')))
13
+
14
+
15
+ ENCRYPTED = 'encrypted'
16
+ ZIPENCRYPTED = 'zipencrypted'
17
+
18
+
19
+ class CryptshieldError(Exception):
20
+ pass
21
+
22
+
23
+ def secure_delete(*paths) -> List[str]:
24
+ """
25
+ Securely deletes a file or directory at the specified path.
26
+
27
+ Args:
28
+ path (str): The path to the file or directory to be deleted.
29
+
30
+ """
31
+ deleted_paths = []
32
+ paths = expand_path(paths)
33
+ total = count_files_and_dirs(paths)
34
+ deleted_count = 0
35
+
36
+ for path in paths:
37
+ if not os.path.exists(path):
38
+ logging.error(f"Path '{path}' does not exist.")
39
+ continue
40
+
41
+ if os.path.isdir(path):
42
+ for root, dirs, files in os.walk(path, topdown=False):
43
+ for file in files:
44
+ file_path = os.path.join(root, file)
45
+ try:
46
+ logging.info(f"({deleted_count + 1}/{total}) Deleting '{file_path}'...")
47
+ subprocess.run(["shred", "-f", "-u", "-n", "3", "-z", file_path], check=True)
48
+ deleted_paths.append(file_path)
49
+ deleted_count += 1
50
+ except subprocess.CalledProcessError as e:
51
+ logging.error(f"Error deleting file '{file_path}': {e}")
52
+
53
+ for dir_ in dirs:
54
+ dir_path = os.path.join(root, dir_)
55
+ try:
56
+ logging.info(f"({deleted_count + 1}/{total}) Deleting '{dir_path}'...")
57
+ os.rmdir(dir_path)
58
+ deleted_paths.append(dir_path)
59
+ deleted_count += 1
60
+ except OSError as e:
61
+ logging.error(f"Error deleting directory '{dir_path}': {e}")
62
+
63
+ try:
64
+ logging.info(f"({deleted_count + 1}/{total}) Deleting '{path}'...")
65
+ os.rmdir(path)
66
+ deleted_paths.append(path)
67
+ deleted_count += 1
68
+ except OSError as e:
69
+ logging.error(f"Error deleting directory '{path}': {e}")
70
+
71
+ else:
72
+ try:
73
+ logging.info(f"({deleted_count + 1}/{total}) Deleting '{path}'...")
74
+ subprocess.run(["shred", "-f", "-u", "-n", "3", "-z", path], check=True)
75
+ deleted_paths.append(path)
76
+ deleted_count += 1
77
+ except subprocess.CalledProcessError as e:
78
+ logging.error(f"Error deleting file '{path}': {e}")
79
+
80
+ logging.info(f"Deleted {deleted_count} files and directories.")
81
+ return deleted_paths
82
+
83
+
84
+ def encrypt(path: str, key: str, delete: bool = True):
85
+ """
86
+ Encrypts files at a given path using a provided key.
87
+
88
+ Args:
89
+ path (str): The path to the file or directory to be encrypted.
90
+ key (str): The key to be used for encryption.
91
+ delete (bool, optional): If True, the original file will be deleted
92
+ after encryption. Defaults to True.
93
+
94
+ This function recursively encrypts all files in the specified directory.
95
+ Encrypted files are saved with the '.encrypted' extension. If the path is a
96
+ directory, it will be compressed into a ZIP file before encryption.
97
+
98
+ Example:
99
+ ```
100
+ key = 'secret_key'
101
+ path = '/path/to/file_or_directory'
102
+ encrypt(path, key)
103
+ ```
104
+ """
105
+
106
+ if delete and has_non_writable(path):
107
+ if not confirm(f'At least one file in "{path}" is not writable. Continue? [y/N] '):
108
+ return
109
+
110
+ if os.path.isdir(path):
111
+
112
+ # First, compress the directory into a ZIP file
113
+ logging.info(f'Compressing directory "{path}"...')
114
+ subprocess.run(['zip', '-r', f'{path}.zip', path], check=True)
115
+
116
+ # Encrypt the ZIP file
117
+ encrypt(f'{path}.zip', key, delete=False)
118
+
119
+ # Rename the encrypted ZIP file to '.zipencrypted'.
120
+ os.rename(f'{path}.zip.{ENCRYPTED}', f'{path}.{ZIPENCRYPTED}')
121
+
122
+ # Delete the original directory and ZIP file
123
+ logging.info(f'Deleting "{path}.zip"...')
124
+ secure_delete(f'{path}.zip')
125
+ if delete:
126
+ logging.info(f'Deleting "{path}"...')
127
+ secure_delete(path)
128
+
129
+ elif os.path.isfile(path) or os.path.islink(path):
130
+ logging.info(f'Encrypting "{path}"...')
131
+ with open(path, 'rb') as file:
132
+ text = file.read()
133
+ encrypted_text = encrypt_text(text, key)
134
+ with open(path + f'.{ENCRYPTED}', 'wb') as encrypted_file:
135
+ encrypted_file.write(encrypted_text)
136
+
137
+ if delete:
138
+ logging.info(f'Deleting "{path}"...')
139
+ secure_delete(path)
140
+
141
+ else:
142
+ raise CryptshieldError(f'"{path}" is not a valid file or directory.')
143
+
144
+
145
+ def decrypt(path: str, key: str, delete: bool = True):
146
+ """
147
+ Decrypts encrypted files at a given path using a provided key.
148
+
149
+ Args:
150
+ path (str): The path to the file or directory to be decrypted.
151
+ key (str): The key to be used for decryption.
152
+ delete (bool, optional): If True, the encrypted file will be deleted
153
+ after decryption. Defaults to True.
154
+
155
+ This function recursively decrypts all files in the specified directory.
156
+ If the path is a directory, it will decrypt all files within it. Files with
157
+ the '.zipencrypted' extension will be decompressed after decryption.
158
+
159
+ Example:
160
+ ```
161
+ key = 'secret_key'
162
+ path = '/path/to/encrypted_file_or_directory'
163
+ decrypt(path, key)
164
+ ```
165
+ """
166
+ if delete and has_non_writable(path):
167
+ if not confirm(f'At least one file in "{path}" is not writable. Continue? [y/N] '):
168
+ return
169
+
170
+ if os.path.isdir(path):
171
+ for filename in os.listdir(path):
172
+ _path = os.path.join(path, filename)
173
+ decrypt(_path, key, delete=delete)
174
+
175
+ elif os.path.isfile(path) or os.path.islink(path):
176
+ logging.info(f'Decrypting "{path}"...')
177
+ with open(path, 'rb') as encrypted_file:
178
+ encrypted_text = encrypted_file.read()
179
+ text = decrypt_text(encrypted_text, key, to_str=False)
180
+
181
+ # Check if the file is a ZIP file that was encrypted
182
+ if path.endswith(f'.{ZIPENCRYPTED}'):
183
+ # Save the decrypted ZIP file
184
+ with open(path.replace(f'.{ZIPENCRYPTED}', '.zip', 1), 'wb') as file:
185
+ file.write(text)
186
+
187
+ # Decompress the ZIP file
188
+ logging.info(f'Decompressing "{path.replace(f".{ZIPENCRYPTED}", ".zip", 1)}"...')
189
+ subprocess.run(['unzip', path.replace(f'.{ZIPENCRYPTED}', '.zip', 1)], check=True)
190
+
191
+ # Delete the encrypted ZIP file
192
+ if delete:
193
+ logging.info(f'Deleting "{path}"...')
194
+ secure_delete(path.replace(f'.{ZIPENCRYPTED}', '.zip', 1))
195
+ secure_delete(path)
196
+ else:
197
+ with open(path.replace(f'.{ENCRYPTED}', '', 1), 'wb') as file:
198
+ file.write(text)
199
+
200
+ # Delete the encrypted file
201
+ if delete:
202
+ logging.info(f'Deleting "{path}"...')
203
+ secure_delete(path)
204
+
205
+ else:
206
+ raise CryptshieldError(f'"{path}" is not valid file or directory.')
207
+
208
+
209
+ def encrypt_text(text: str | bytes, key: str = None) -> bytes:
210
+ """
211
+ Encrypts a text or bytes using a provided key.
212
+
213
+ Args:
214
+ text (str | bytes): The text or bytes to be encrypted.
215
+ key (str): The key to be used for encryption.
216
+
217
+ Returns:
218
+ bytes: The encrypted text as bytes.
219
+
220
+ This function uses the Fernet symmetric encryption algorithm to encrypt
221
+ the provided text or bytes.
222
+
223
+ Example:
224
+ ```
225
+ key = 'secret_key'
226
+ text = 'This is a confidential message.'
227
+ encrypted_text = encrypt_text(text, key)
228
+ ```
229
+ """
230
+ if not key:
231
+ key = get_default_key()
232
+ logging.debug(f'Using default key: {key}')
233
+
234
+ bkey = get_fernet_key(key)
235
+ fernet = Fernet(bkey)
236
+ bytes_text = text if isinstance(text, bytes) else text.encode()
237
+ encrypted_text = fernet.encrypt(bytes_text)
238
+ return encrypted_text
239
+
240
+
241
+ def decrypt_text(encrypted_text: str, key: str, to_str: bool = True) -> str | bytes:
242
+ """
243
+ Decrypts an encrypted text using the provided key.
244
+
245
+ Args:
246
+ encrypted_text (str): The encrypted text to be decrypted.
247
+ key (str): The key to be used for decryption.
248
+
249
+ Returns:
250
+ str | bytes: The decrypted text.
251
+
252
+ This function uses the Fernet symmetric encryption algorithm to decrypt the
253
+ provided text. The key must match the one used for encryption, otherwise
254
+ a CryptshieldError will be raised.
255
+
256
+ Example:
257
+ ```
258
+ key = 'secret_key'
259
+ encrypted_text = '...'
260
+ decrypted_text = decrypt_text(encrypted_text, key)
261
+ ```
262
+ """
263
+ if not key:
264
+ key = get_default_key()
265
+ logging.debug(f'Using default key: {key}')
266
+
267
+ bkey = get_fernet_key(key)
268
+ fernet = Fernet(bkey)
269
+
270
+ try:
271
+ decrypted_bytes = fernet.decrypt(encrypted_text)
272
+ except InvalidToken as e:
273
+ raise CryptshieldError(f'Invalid key: {e}')
274
+
275
+ if to_str:
276
+ return decrypted_bytes.decode('utf-8', errors='ignore')
277
+
278
+ return decrypted_bytes
279
+
280
+
281
+ def get_default_key() -> str:
282
+ machine_id = subprocess.run(['cat', '/etc/machine-id'], capture_output=True, text=True).stdout.strip()
283
+ user_id = subprocess.run(['id', '-u'], capture_output=True, text=True).stdout.strip()
284
+ combined = f"{machine_id}-{user_id}"
285
+ key = hashlib.sha256(combined.encode()).hexdigest()
286
+ return key
287
+
288
+
289
+ def get_fernet_key(key: str) -> bytes:
290
+ """
291
+ Generates a Fernet key from a provided key.
292
+
293
+ Args:
294
+ key (str): The key to be used for generating the Fernet key.
295
+
296
+ Returns:
297
+ bytes: The generated Fernet key.
298
+
299
+ This function generates a Fernet key using the MD5 hash algorithm.
300
+ The key is necessary for securely encrypting and decrypting text using
301
+ the Fernet encryption scheme.
302
+ """
303
+ passcode = key.encode()
304
+ assert isinstance(passcode, bytes)
305
+ hlib = hashlib.md5()
306
+ hlib.update(passcode)
307
+ return base64.urlsafe_b64encode(hlib.hexdigest().encode())
308
+
309
+
310
+ def has_non_writable(path: str) -> bool:
311
+ """
312
+ Checks whether a file or directory (including its contents if it's a directory)
313
+ contains at least one file or subdirectory without write permissions.
314
+
315
+ Args:
316
+ path (str): The path to the file or directory to be checked.
317
+
318
+ Returns:
319
+ bool: True if at least one file or subdirectory lacks write permissions,
320
+ False otherwise.
321
+
322
+ Raises:
323
+ FileNotFoundError: If the specified path does not exist.
324
+
325
+ This function recursively checks the write permissions of all files and
326
+ subdirectories within the given path. If the path points to a file, it
327
+ checks the write permissions of that file directly. If the path points to a
328
+ directory, it traverses the directory tree and checks the write permissions
329
+ of all files and subdirectories.
330
+ """
331
+ if not os.path.exists(path):
332
+ raise FileNotFoundError(f"Path '{path}' does not exist.")
333
+
334
+ if os.path.isfile(path):
335
+ return not os.access(path, os.W_OK)
336
+
337
+ for root, dirs, files in os.walk(path):
338
+ for name in dirs + files:
339
+ if not os.access(os.path.join(root, name), os.W_OK):
340
+ return True
341
+
342
+ return False
343
+
344
+
345
+ def expand_path(pattern: str | List[str]) -> List[str]:
346
+ """
347
+ Expands a path pattern into a list of matching file paths.
348
+
349
+ Args:
350
+ pattern (str | List[str]): The path pattern to be expanded.
351
+
352
+ Returns:
353
+ List[str]: A list of matching file paths.
354
+ """
355
+ if isinstance(pattern, str):
356
+ pattern = [pattern]
357
+
358
+ matches = []
359
+ for p in pattern:
360
+ expanded = os.path.expanduser(p)
361
+ # Include hidden files and directories
362
+ _matches = glob.glob(expanded, recursive=True) + glob.glob(os.path.join(expanded, '.*'), recursive=True)
363
+ matches.extend(_matches)
364
+ return matches
365
+
366
+
367
+ def count_files_and_dirs(paths):
368
+ """
369
+ Counts the number of files and directories in the specified paths.
370
+ """
371
+ total = 0
372
+ for path in paths:
373
+ if os.path.isdir(path):
374
+ for _, dirs, files in os.walk(path):
375
+ total += len(files) + len(dirs)
376
+ total += 1
377
+ elif os.path.isfile(path):
378
+ total += 1
379
+ return total
380
+
381
+
382
+ def confirm(prompt: str) -> bool:
383
+ confirm = input(prompt)
384
+ if confirm.lower() in ('y', 'yes'):
385
+ return True
386
+ return False
387
+
388
+
389
+ def set_logging(
390
+ name=None,
391
+ level=logging.DEBUG,
392
+ filename='app.log',
393
+ formatter='%(levelname)s - %(message)s',
394
+ ):
395
+ logger = logging.getLogger(name)
396
+ logger.setLevel(level)
397
+
398
+ # Create console handler and set level to INFO
399
+ console_handler = logging.StreamHandler()
400
+ console_handler.setLevel(level)
401
+ console_formatter = logging.Formatter('%(message)s')
402
+ console_handler.setFormatter(console_formatter)
403
+ logger.addHandler(console_handler)
404
+
405
+ if filename:
406
+ # Create file handler and set level to INFO
407
+ file_info_handler = logging.FileHandler(filename, mode='w')
408
+ file_info_handler.setLevel(logging.INFO)
409
+ file_formatter = logging.Formatter(formatter)
410
+ file_info_handler.setFormatter(file_formatter)
411
+ logger.addHandler(file_info_handler)
412
+
413
+
414
+ # Mapping commands to their respective functions
415
+ COMMAND_MAP = {
416
+ "delete": secure_delete,
417
+ "encrypt": encrypt,
418
+ "decrypt": decrypt,
419
+ "encrypt_text": encrypt_text,
420
+ "decrypt_text": decrypt_text,
421
+ }
422
+
423
+
424
+ def show_help():
425
+ """
426
+ Displays usage instructions.
427
+ """
428
+ print(
429
+ """
430
+ Usage: cryptshield <command> [options]
431
+
432
+ Commands:
433
+ delete <path>...: Securely delete files or directories.
434
+ encrypt <path> <key> [--delete]: Encrypt files or directories.
435
+ decrypt <path> <key> [--delete]: Decrypt encrypted files or directories.
436
+ encrypt_text <text> <key>: Encrypt text using a key.
437
+ decrypt_text <text> <key>: Decrypt encrypted text using a key.
438
+ help: Show this help message.
439
+ """
440
+ )
441
+
442
+
443
+ def main():
444
+ print(sys.argv)
445
+ if len(sys.argv) < 2:
446
+ print(f"Missing arguments. {sys.argv=}")
447
+ show_help()
448
+ sys.exit(1)
449
+
450
+ command_name = sys.argv[1]
451
+ options = sys.argv[2:]
452
+
453
+ if command_name in ("help", "h"):
454
+ print("Showing help:")
455
+ show_help()
456
+ sys.exit(0)
457
+
458
+ if command_name not in COMMAND_MAP:
459
+ print(f'Invalid command: "{command_name}".')
460
+ show_help()
461
+ sys.exit(1)
462
+
463
+ command = COMMAND_MAP[command_name]
464
+
465
+ # Execute command
466
+ try:
467
+ result = command(*options)
468
+ if result is not None:
469
+ print(result)
470
+ except CryptshieldError as e:
471
+ print(f'Error executing command "{command_name}": {str(e)}')
472
+ sys.exit(1)
473
+
474
+
475
+ if __name__ == "__main__":
476
+ set_logging()
477
+ main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: cryptshield
3
- Version: 1.0.0
3
+ Version: 1.0.1
4
4
  Summary: Secure Encryption and Deletion Application
5
5
  Author-email: Wilmer Martinez <info@wilmermartinez.dev>
6
6
  License: MIT License
@@ -2,6 +2,8 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  setup.py
5
+ src/cryptshield/__init__.py
6
+ src/cryptshield/cryptshield.py
5
7
  src/cryptshield.egg-info/PKG-INFO
6
8
  src/cryptshield.egg-info/SOURCES.txt
7
9
  src/cryptshield.egg-info/dependency_links.txt
@@ -0,0 +1 @@
1
+ cryptshield
@@ -1,15 +0,0 @@
1
- from setuptools import setup
2
-
3
- setup(
4
- name="cryptshield",
5
- version="1.0",
6
- packages=["src"],
7
- install_requires=[
8
- "cryptography",
9
- ],
10
- entry_points={
11
- "console_scripts": [
12
- "cryptshield=src.cryptshield:main",
13
- ]
14
- },
15
- )
File without changes
File without changes
File without changes