Skip to content

Instantly share code, notes, and snippets.

@renepardon
Created May 12, 2026 17:55
Show Gist options
  • Select an option

  • Save renepardon/cb6ff70eada66421bb2e8f6f73290de9 to your computer and use it in GitHub Desktop.

Select an option

Save renepardon/cb6ff70eada66421bb2e8f6f73290de9 to your computer and use it in GitHub Desktop.
decrypt encrypted file
import sys
import os
def xor_bytes(data: bytes, key: bytes) -> bytes:
"""
Performs a repeating-key XOR operation on the given data using the key.
XOR decryption is the same as encryption.
If the key is shorter than the data, it is cycled.
"""
key_length = len(key)
# Each byte in 'data' is XORed with the corresponding byte in 'key' (cycled)
return bytes(data[i] ^ key[i % key_length] for i in range(len(data)))
def main():
"""
Main entry point for the XOR decryption script.
Handles arguments, validates files, and performs decryption.
"""
# 1. Accepts the encrypted file and key file as command-line arguments; print usage and exit if missing.
if len(sys.argv) < 3:
print("Usage: python3 xor_decrypt.py <encrypted_file> <key_file>")
sys.exit(1)
encrypted_file_path = sys.argv[1]
key_file_path = sys.argv[2]
# 2. Validates both files exist; print a distinct error message for each missing file.
if not os.path.exists(encrypted_file_path):
print(f"Error: Encrypted file '{encrypted_file_path}' does not exist.")
sys.exit(1)
if not os.path.exists(key_file_path):
print(f"Error: Key file '{key_file_path}' does not exist.")
sys.exit(1)
try:
# Read the encrypted data
with open(encrypted_file_path, 'rb') as f:
ciphertext = f.read()
# Read the key
with open(key_file_path, 'rb') as f:
key = f.read()
if not key:
print("Error: Key file is empty.")
sys.exit(1)
# 3. XOR-decrypts the file
plaintext = xor_bytes(ciphertext, key)
# 4. Writes the result as <name>_decrypted<ext>
file_root, file_ext = os.path.splitext(encrypted_file_path)
output_path = f"{file_root}_decrypted{file_ext}"
with open(output_path, 'wb') as f:
f.write(plaintext)
# 5. Prints the output path to the terminal.
print(f"Decrypted : {output_path}")
except Exception as e:
print(f"An error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment