Last active
June 5, 2023 17:14
-
-
Save joshfinley/9b12fcb96834435aaa66d1affd73c0cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import base64 | |
def xor_encrypt_decrypt(data, key): | |
encrypted_data = [] | |
for byte in data: | |
encrypted_byte = byte ^ key | |
encrypted_data.append(encrypted_byte) | |
return bytes(encrypted_data) | |
def is_base64(s): | |
try: | |
# Attempt to decode the string as base64 | |
base64.b64decode(s) | |
return True | |
except: | |
return False | |
def base64_encode_file(file_path, key): | |
try: | |
with open(file_path, 'rb') as file: | |
contents = file.read() | |
if not is_base64(contents): | |
# If contents are plain text, encrypt and encode them | |
encrypted_data = xor_encrypt_decrypt(contents, key) | |
encoded = base64.b64encode(encrypted_data).decode() | |
with open(file_path, 'w') as encoded_file: | |
encoded_file.write(encoded) | |
print(f"File {file_path} encrypted and base64 encoded successfully.") | |
else: | |
print(f"File {file_path} is already base64 encoded.") | |
except FileNotFoundError: | |
print(f"File {file_path} not found.") | |
def base64_decode_file(file_path, key): | |
try: | |
with open(file_path, 'r') as file: | |
contents = file.read() | |
if is_base64(contents): | |
# If contents are base64 encoded, decode and decrypt them | |
decoded_data = base64.b64decode(contents) | |
decrypted_data = xor_encrypt_decrypt(decoded_data, key) | |
with open(file_path, 'wb') as decoded_file: | |
decoded_file.write(decrypted_data) | |
print(f"File {file_path} base64 decoded and decrypted successfully.") | |
else: | |
print(f"File {file_path} is not base64 encoded.") | |
except FileNotFoundError: | |
print(f"File {file_path} not found.") | |
if __name__ == "__main__": | |
if len(sys.argv) != 4: | |
print("Usage: python base64_encrypt_decrypt.py <encode|decode> <file_path> <key>") | |
sys.exit(1) | |
action = sys.argv[1] | |
file_path = sys.argv[2] | |
key = int(sys.argv[3]) | |
if action == "encode": | |
base64_encode_file(file_path, key) | |
elif action == "decode": | |
base64_decode_file(file_path, key) | |
else: | |
print("Invalid action. Use 'encode' or 'decode'.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment