Skip to content

Commit d42ba88

Browse files
committed
Added error handling to CodeSafe, and removed some print statements with edits from @0XC7R.
1 parent 9e20a23 commit d42ba88

File tree

2 files changed

+116
-69
lines changed

2 files changed

+116
-69
lines changed

codesafe/__init__.py

Lines changed: 115 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -204,33 +204,54 @@ def encrypt_to_file(code: str, output_file: str, mapping: dict = _character_map)
204204
Returns:
205205
None
206206
"""
207-
# Step 1: Encrypt using mapping
208-
mapped_encrypted = encrypt_with_mapping(code, mapping)
209-
210-
# Step 2: Caesar Cipher
211-
caesar_encrypted = caesar_cipher(mapped_encrypted, SHIFT)
212-
213-
# Step 3: Base64 Encoding
214-
base64_encoded = base64.b64encode(caesar_encrypted.encode()).decode()
215-
216-
# Write the encrypted code as comments in the Python file
217-
with open(output_file, 'w') as file:
218-
file.write(f"# {base64_encoded}")
207+
try:
208+
# Step 1: Encrypt using mapping
209+
mapped_encrypted = encrypt_with_mapping(code, mapping)
210+
if not mapped_encrypted:
211+
raise ValueError("Mapping encryption failed. The result is empty.")
212+
213+
# Step 2: Caesar Cipher
214+
caesar_encrypted = caesar_cipher(mapped_encrypted, SHIFT)
215+
if not caesar_encrypted:
216+
raise ValueError("Caesar cipher encryption failed. The result is empty.")
217+
218+
# Step 3: Base64 Encoding
219+
base64_encoded = base64.b64encode(caesar_encrypted.encode()).decode()
220+
if not base64_encoded:
221+
raise ValueError("Base64 encoding failed. The result is empty.")
222+
223+
try:
224+
# Write the encrypted code as comments in the Python file
225+
with open(output_file, 'w') as file:
226+
file.write(f"# {base64_encoded}")
227+
except IOError as e:
228+
raise IOError(f"Failed to write to file '{output_file}': {e}")
219229

220-
print(f"Code encrypted and saved to {output_file}")
230+
except Exception as e:
231+
raise RuntimeError(f"An error occurred during encryption: {e}")
221232

222233
def decrypt_code(encrypted_code: str, mapping: dict) -> str:
223234
"""Decrypts the encrypted code using the reverse of the encryption methods."""
224-
# Step 1: Decode from Base64
225-
base64_decoded = base64.b64decode(encrypted_code).decode()
235+
try:
236+
# Step 1: Decode from Base64
237+
base64_decoded = base64.b64decode(encrypted_code).decode()
238+
if not base64_decoded:
239+
raise ValueError("Base64 decryption failed. The result is empty.")
240+
241+
# Step 2: Apply the reverse Caesar cipher
242+
caesar_decoded = caesar_cipher(base64_decoded, -SHIFT)
243+
if not caesar_decoded:
244+
raise ValueError("Caesar cipher decryption failed. The result is empty.")
226245

227-
# Step 2: Apply the reverse Caesar cipher
228-
caesar_decoded = caesar_cipher(base64_decoded, -SHIFT)
246+
# Step 3: Decrypt using mapping
247+
original_code = decrypt_with_mapping(caesar_decoded, mapping)
248+
if not original_code:
249+
raise ValueError("Mapping decryption failed. The result is empty.")
229250

230-
# Step 3: Decrypt using mapping
231-
original_code = decrypt_with_mapping(caesar_decoded, mapping)
251+
return original_code
232252

233-
return original_code
253+
except Exception as e:
254+
raise RuntimeError(f"An error occurred during decryption: {e}")
234255

235256
def encrypt(code:str, mapping: dict = _character_map) -> str:
236257
"""
@@ -243,17 +264,25 @@ def encrypt(code:str, mapping: dict = _character_map) -> str:
243264
Returns:
244265
str: The encrypted code.
245266
"""
246-
247-
# Step 1: Encrypt using mapping
248-
mapped_encrypted = encrypt_with_mapping(code, mapping)
249-
250-
# Step 2: Caesar Cipher
251-
caesar_encrypted = caesar_cipher(mapped_encrypted, SHIFT)
252-
253-
# Step 3: Base64 Encoding
254-
base64_encoded = base64.b64encode(caesar_encrypted.encode()).decode()
255-
256-
return base64_encoded
267+
try:
268+
# Step 1: Encrypt using mapping
269+
mapped_encrypted = encrypt_with_mapping(code, mapping)
270+
if not mapped_encrypted:
271+
raise ValueError("Mapping encryption failed. The result is empty.")
272+
273+
# Step 2: Caesar Cipher
274+
caesar_encrypted = caesar_cipher(mapped_encrypted, SHIFT)
275+
if not caesar_encrypted:
276+
raise ValueError("Caesar cipher encryption failed. The result is empty.")
277+
278+
# Step 3: Base64 Encoding
279+
base64_encoded = base64.b64encode(caesar_encrypted.encode()).decode()
280+
if not base64_encoded:
281+
raise ValueError("Base64 encoding failed. The result is empty.")
282+
283+
return base64_encoded
284+
except Exception as e:
285+
raise RuntimeError(f"An error occurred during encryption: {e}")
257286

258287
def decrypt(encrypted_code:str, mapping: dict =_character_map) -> str:
259288
"""
@@ -266,17 +295,25 @@ def decrypt(encrypted_code:str, mapping: dict =_character_map) -> str:
266295
Returns:
267296
str: The decrypted code.
268297
"""
269-
270-
# Step 1: Decode from Base64
271-
base64_decoded = base64.b64decode(encrypted_code).decode()
272-
273-
# Step 2: Apply the reverse Caesar cipher
274-
caesar_decoded = caesar_cipher(base64_decoded, -SHIFT)
275-
276-
# Step 3: Decrypt using mapping
277-
original_code = decrypt_with_mapping(caesar_decoded, mapping)
278-
279-
return original_code
298+
try:
299+
# Step 1: Decode from Base64
300+
base64_decoded = base64.b64decode(encrypted_code).decode()
301+
if not base64_decoded:
302+
raise ValueError("Base64 decryption failed. The result is empty.")
303+
304+
# Step 2: Apply the reverse Caesar cipher
305+
caesar_decoded = caesar_cipher(base64_decoded, -SHIFT)
306+
if not caesar_decoded:
307+
raise ValueError("Caesar cipher decryption failed. The result is empty.")
308+
309+
# Step 3: Decrypt using mapping
310+
original_code = decrypt_with_mapping(caesar_decoded, mapping)
311+
if not original_code:
312+
raise ValueError("Mapping decryption failed. The result is empty.")
313+
314+
return original_code
315+
except Exception as e:
316+
raise RuntimeError(f"An error occurred during decryption: {e}")
280317

281318
def run(encrypted_file: str, mapping: dict = _character_map) -> bool:
282319
"""
@@ -293,22 +330,18 @@ def run(encrypted_file: str, mapping: dict = _character_map) -> bool:
293330
# Read the encrypted code from the file
294331
with open(encrypted_file, 'r') as file:
295332
content = file.read()
296-
333+
297334
# Extract the encrypted code from the comments
298335
encrypted_code = re.search(r'# (.+)', content).group(1)
299336
encrypted_code = encrypted_code.replace("# ", '')
300-
337+
301338
# Decrypt the code
302339
decrypted_code = decrypt_code(encrypted_code, mapping)
303-
340+
304341
# Execute the decrypted Python code
305342
exec(decrypted_code)
306-
307-
# I modify the print statement global so this will break for me.
308-
#print("Code decrypted and executed successfully.")
309-
return true
310-
except Exception:
311-
return false
343+
except Exception as e:
344+
raise RuntimeError(f"An error occurred during decryption and execution: {e}")
312345

313346
def decrypt_to_file(encrypted_file: str, output_file: str, mapping: dict = _character_map) -> bool:
314347
"""
@@ -323,24 +356,38 @@ def decrypt_to_file(encrypted_file: str, output_file: str, mapping: dict = _char
323356
None
324357
"""
325358
try:
326-
359+
# Check if the mapping is valid
360+
if not isinstance(mapping, dict):
361+
raise ValueError("The mapping parameter must be a dictionary.")
362+
327363
# Read the encrypted code from the file
328-
with open(encrypted_file, 'r') as file:
329-
content = file.read()
330-
364+
try:
365+
with open(encrypted_file, 'r') as file:
366+
content = file.read()
367+
except FileNotFoundError:
368+
raise FileNotFoundError(f"The file {encrypted_file} does not exist.")
369+
except IOError as e:
370+
raise IOError(f"An error occurred while reading the file {encrypted_file}: {e}")
371+
331372
# Extract the encrypted code from the comments
332-
encrypted_code = re.search(r'# (.+)', content).group(1)
333-
encrypted_code = encrypted_code.replace("# ", '')
334-
373+
match = re.search(r'# (.+)', content)
374+
if not match:
375+
raise ValueError("No encrypted code found in the file. Ensure the file contains a valid encrypted comment.")
376+
377+
encrypted_code = match.group(1).replace("# ", '')
378+
335379
# Decrypt the code
336-
decrypted_code = decrypt_code(encrypted_code, mapping)
337-
380+
try:
381+
decrypted_code = decrypt_code(encrypted_code, mapping)
382+
except Exception as e:
383+
raise ValueError(f"An error occurred during decryption: {e}")
384+
338385
# Write the decrypted code to the specified output file
339-
with open(output_file, 'w') as file:
340-
file.write(decrypted_code)
341-
342-
# I modify the print global so this will break for me.
343-
#print(f"Decrypted code written to {output_file}.")
344-
return true
345-
except Exception:
346-
return false
386+
try:
387+
with open(output_file, 'w') as file:
388+
file.write(decrypted_code)
389+
except IOError as e:
390+
raise IOError(f"An error occurred while writing to the file {output_file}: {e}")
391+
392+
except Exception as e:
393+
print(f"An error occurred during decryption to file: {e}")

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
url='https://github.com/infinitode/codesafe',
1515
packages=find_packages(),
1616
classifiers=[
17-
'Development Status :: 3 - Alpha',
17+
'Development Status :: 5 - Production/Stable',
1818
'Intended Audience :: Developers',
1919
'License :: OSI Approved :: MIT License',
2020
'Programming Language :: Python :: 3.6',

0 commit comments

Comments
 (0)