Skip to content

Instantly share code, notes, and snippets.

@tmessinis
Last active July 28, 2016 01:28
Show Gist options
  • Save tmessinis/8eee001ca4d24ab8d02ce62a1d51ac06 to your computer and use it in GitHub Desktop.
Save tmessinis/8eee001ca4d24ab8d02ce62a1d51ac06 to your computer and use it in GitHub Desktop.
An implementation of a simple caesar cipher
# This is an attempt at creating a caesar cipher using the ord()
# function and taking input from the user.
import re
def caesar_cipher(mode, input_str, key):
return_str = ''
char_as_num = None
num_as_char = None
char_after_cipher = None
if mode == 'ENCRYPT':
for char in input_str:
char_as_num = ord(char)
char_after_cipher = char_as_num + (key % 26)
if re.match(r"[^A-Za-z]", char):
return_str += char
elif char == char.upper():
if char_after_cipher > 90:
num_as_char = chr(char_after_cipher - 26)
return_str += num_as_char
else:
num_as_char = chr(char_after_cipher)
return_str += num_as_char
else:
if char_after_cipher > 122:
num_as_char = chr(char_after_cipher - 26)
return_str += num_as_char
else:
num_as_char = chr(char_after_cipher)
return_str += num_as_char
if mode == 'DECRYPT':
for char in input_str:
char_as_num = ord(char)
char_after_cipher = char_as_num - (key % 26)
if re.match(r"[^A-Za-z]", char):
return_str += char
elif char == char.upper():
if char_after_cipher < 65:
num_as_char = chr(char_after_cipher + 26)
return_str += num_as_char
else:
num_as_char = chr(char_after_cipher)
return_str += num_as_char
else:
if char_after_cipher < 97:
num_as_char = chr(char_after_cipher + 26)
return_str += num_as_char
else:
num_as_char = chr(char_after_cipher)
return_str += num_as_char
return return_str
def validate_entry(variable, input_str):
return_input = input_str
while True:
if variable == 'mode' and return_input.upper() not in ('ENCRYPT', 'DECRYPT'):
print('"{0}" is not a valid input for mode...'.format(return_input))
return_input = input('> ')
else:
break
return return_input
def main():
mode = None
input_str = None
result = None
key = None
print('Welcome to a simple caesar cipher!')
mode = input('Choose mode (encrypt/decrypt): ')
mode = validate_entry('mode', mode)
print('')
print('Enter the string that you want to {0}:'.format(mode.lower()))
input_str = input()
print('')
key = input('Choose key (any non-negative/non-decimal number): ')
print('')
result = caesar_cipher(mode.upper(), input_str, int(key))
print('Result: {0}'.format(result))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment