Created
December 19, 2016 20:36
-
-
Save mmafrar/756937aca05012d5d4972bfd244b904a to your computer and use it in GitHub Desktop.
A simple demonstration of Caeser Cipher algorithm implemented using Python.
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
# Caesar Cipher | |
import sys | |
MAX_KEY_SIZE = 26 | |
def getMode(): | |
while True: | |
print('Do you wish to encrypt or decrypt a message?') | |
mode = input().lower() | |
if mode in 'encrypt e decrypt d'.split(): | |
return mode | |
else: | |
print('Enter either "encrypt" or "e" or "decrypt" or "d".') | |
def getKey(): | |
key = 0 | |
while True: | |
key = int(sys.argv[1]) | |
if (key >= 1 and key <= MAX_KEY_SIZE): | |
return key | |
def getTranslatedMessage(mode, message, key): | |
if mode[0] == 'd': | |
key = -key | |
translated = '' | |
for symbol in message: | |
if symbol.isalpha(): | |
num = ord(symbol) | |
num += key | |
if symbol.isupper(): | |
if num > ord('Z'): | |
num -= 26 | |
elif num < ord('A'): | |
num += 26 | |
elif symbol.islower(): | |
if num > ord('z'): | |
num -= 26 | |
elif num < ord('a'): | |
num += 26 | |
translated += chr(num) | |
else: | |
translated += symbol | |
return translated | |
mode = getMode() | |
key = getKey() | |
print('Enter your input filename: ') | |
file_in = input() | |
fin = open(file_in, 'r') | |
print('Enter your output filename: ') | |
file_in = input() | |
fout = open(file_in, 'w') | |
for line in fin: | |
fout.write(getTranslatedMessage(mode, line, key)) | |
fout.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment