Skip to content

Instantly share code, notes, and snippets.

@kellyelton
Created October 29, 2019 06:29
Show Gist options
  • Save kellyelton/013b4ce332a54db1c5147e8dab26d5b0 to your computer and use it in GitHub Desktop.
Save kellyelton/013b4ce332a54db1c5147e8dab26d5b0 to your computer and use it in GitHub Desktop.
Loran Cipher
'''
By Loran E.
Caesar Cipher w/ range to ascii table
A true Caesar Cipher would only inlcude the alphabet
ascii table: 127
extended: 255
'''
'''
Powershell Instructions:
"This is a message" > message.txt
cat message.txt | py CaeserCypher.py encrypt UserKey > encrypted.txt
cat encrypted.txt | py CaeserCypher.py decrypt UserKey > decrypted.txt
type decrpted.txt
'''
# include standard modules
import argparse, sys
class CaesarCipher:
def __init__(self, user_key):
self.user_key = user_key
def encrypt(self, user_input):
buffer_message = ""
new_message = ""
for x in range(len(user_input)):
buffer_message = (ord(user_input[x]) + ord(self.user_key[x % len(self.user_key)]))
new_message += chr(buffer_message % 127)
return(new_message)
def decrypt(self, user_input):
buffer_message = ""
new_message = ""
for x in range(len(user_input)):
buffer_message = (ord(user_input[x]) - ord(self.user_key[x % len(self.user_key)]))
new_message += chr(buffer_message % 127)
return(new_message)
class InvalidConfig(Exception):
def __init__(self, config_name, config_value):
Exception.__init__(self, f'The config {config_name} "{config_value}" is invalid')
class Config:
mode: str
key: str
def validate(self):
if self.mode != "encrypt" and self.mode != "decrypt":
raise InvalidConfig("mode", self.mode)
if len(self.key) is 0:
raise InvalidConfig("key", self.key)
def getConfig():
parser = argparse.ArgumentParser()
parser.add_argument("mode", help="Valid modes are 'encrypt' 'decrypt'", type=str)
parser.add_argument("key", help="Cipher Key", type=str)
# Read and parse command line arguments
args = parser.parse_args()
config = Config()
config.mode = args.mode
config.key = args.key
return config
def getInputData():
inputData = sys.stdin.readlines()
inputData = '\n'.join(inputData)
inputData = inputData.rstrip()
return inputData
#### Start the app
try:
config = getConfig()
config.validate()
inputData = getInputData()
# Do cipher
cipher = CaesarCipher(config.key)
if config.mode == 'encrypt':
print(cipher.encrypt(inputData))
elif config.mode == 'decrypt':
print(cipher.decrypt(inputData))
else:
raise Exception('Invalid Operation')
except InvalidConfig as error:
parser = argparse.ArgumentParser()
parser.add_argument("mode", help="Valid modes are 'encrypt' 'decrypt'", type=str)
parser.add_argument("key", help="Cipher Key", type=str)
errorString = str(error)
parser.error(errorString)
except Exception as error:
traceback.print_tb(error.__traceback__)
exit(-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment