Skip to content

Instantly share code, notes, and snippets.

@montycheese
Created December 1, 2014 01:01
Show Gist options
  • Save montycheese/39d4cc809efd0185ea1f to your computer and use it in GitHub Desktop.
Save montycheese/39d4cc809efd0185ea1f to your computer and use it in GitHub Desktop.
Shift Cypher encryption and decryption
import string
REPLACE_SPACE = None
def map_alphabet():
alphabet = string.lowercase
map = dict()
map[" "] = REPLACE_SPACE # if spaces are found in code
for idx in range(0, 26):
map[alphabet[idx]] = idx
#a = 0, b = 1......z = 25
return map
def encrypt(message, key):
# key is an integer 0-26 that offsets the message before modulation
enum_after_mod = []
encrypted_message = ""
char_mapping = map_alphabet()
for char in message:
try:
enum_after_mod.append((char_mapping[char] + key) % 26)
except TypeError:
enum_after_mod.append(REPLACE_SPACE)
for enumerations in enum_after_mod:
for key in char_mapping.keys():
if enumerations == char_mapping[key]:
encrypted_message += key
return encrypted_message
def decrypt(encrypted_message, key):
enum_after_mod = []
decrypted_message = ""
char_mapping = map_alphabet()
for char in encrypted_message:
try:
enum_after_mod.append((char_mapping[char] - key) % 26)
except TypeError:
enum_after_mod.append(REPLACE_SPACE)
for enumerations in enum_after_mod:
for key in char_mapping.keys():
if enumerations == char_mapping[key]:
decrypted_message += key
return decrypted_message
if __name__ == "__main__":
msg = raw_input("Message to encrypt: ").lower()
k = int(raw_input("Cypher key: "))
encrypted_msg = encrypt(msg, k)
#print encrypted_msg
decrypted_msg = decrypt(encrypted_msg, k)
#print decrypted_msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment