Last active
October 12, 2020 22:57
-
-
Save secoats/c1fc67a45183cdc4b5f04ffc0e327dee to your computer and use it in GitHub Desktop.
Simple XOR Cipher in Python3
This file contains 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
#!/usr/bin/env python3 | |
# Simple XOR cipher | |
# U+0A75 | |
def xor_cipher(data, key): | |
for i in range(len(data)): # iterate through the message bytes | |
j = i % len(key) # rotate index of key bytes (modulo) | |
data[i] = data[i] ^ key[j] # xor current data byte with key byte | |
return data | |
# Example | |
encoding = "utf-8" | |
message = bytearray("Hallo world, such a nice day", encoding) | |
password = bytearray("hunter2!#+", encoding) | |
print(message) | |
encrypted = xor_cipher(data=message, key=password) | |
print(encrypted) # Encrypted message | |
decrypted = xor_cipher(data=encrypted, key=password) | |
print(decrypted) # Original message is restored | |
print(decrypted.decode(encoding)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment