Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AnonymerNiklasistanonym/bb3d75b7eac8443a0b3c11526fd5ab08 to your computer and use it in GitHub Desktop.
Save AnonymerNiklasistanonym/bb3d75b7eac8443a0b3c11526fd5ab08 to your computer and use it in GitHub Desktop.
Encrypt and decrypt a given string with a given key number to a list of numbers string which can be recreated by using the same key number again
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def cipher(text, key):
""" From https://stackoverflow.com/a/17984554/7827128 """
return [(c + key) % 256 for c in text.encode('utf8')]
def decipher(data, key):
""" From https://stackoverflow.com/a/17984554/7827128 """
return bytes([(c - key) % 256 for c in data]).decode('utf8')
def encrypt(message, key):
""" Encrypt a given string """
print('Encrypt "' + message + '" with the key "' + str(key) + '"')
print(' '.join(map(str, cipher(message, key))))
def decrypt(message, key):
""" Decrypt a given string """
print('Decrypt "' + message + '" with the key "' + str(key) + '"')
try:
print(decipher(map(int, message.split(' ')), key))
except ValueError:
print('Error: The message to decrypt is not a list of numbers!')
return 0
def RepresentsInt(s):
""" Check if the given string represents an integer """
try:
int(s)
return True
except ValueError:
return False
def main():
""" Main program """
# Setup variables
decryptBool = True
message = ''
key = False
# Get the if to decrypt or encrypt
for x in sys.argv:
if str(x) == '-e':
decryptBool = False
break
# Get the key
for x in sys.argv:
if RepresentsInt(x):
key = int(x)
break
if not key:
print('Error: No key found!')
return 0
# Get the message
for x in sys.argv:
if str(x) != '-e' and str(x) != '' and not str(x).endswith('.py') and str(x) != str(key):
message = str(x)
break
if message == '':
print('Error: No message found!')
return 0
# Check if decrypt or encrypt
if decryptBool:
decrypt(message, key)
else:
encrypt(message, key)
# Quit successfully
return 0
if __name__ == "__main__":
""" To decrypt a message use as arguments: "encryptedString" keyNumber
To encrypt a string use as arguments: -e "stringToEncrypt" keyNumber """
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment