Skip to content

Instantly share code, notes, and snippets.

@cjanis
Created May 8, 2018 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjanis/f405821b8912520424a2d7de8c8a638c to your computer and use it in GitHub Desktop.
Save cjanis/f405821b8912520424a2d7de8c8a638c to your computer and use it in GitHub Desktop.
A simple numeric cipher created with Python
# create alphabet and digits dictionary
import string
alphabet_master = string.ascii_lowercase + string.digits + ' '
alphabet_master = {a:(alphabet_master.index(a) + 1) for a in alphabet_master}
# the cipher
def cipher(direction,key,message):
# make a copy of the alphabet
alphabet = alphabet_master.copy()
# update alphabet per key
for k,v in alphabet.items():
# add the key to the current value
alphabet[k] += key
# loop around if key > len(alphabet_master)
if alphabet[k] > len(alphabet_master):
alphabet[k] = alphabet[k] - len(alphabet_master)
# encode
if direction == 'encode':
# format message: remove all but alphanumeric and space
import re
message = re.sub('[^\w\s]+','',message).lower()
# encode message
encoded = []
for a in list(message):
encoded.append(str(alphabet[a]))
# return a string of the encoded message
return '/'.join(encoded)
# decode
if direction == 'decode':
# swap k,v in alphabet
alphabet_swapped = {}
for k,v in alphabet.items():
alphabet_swapped[v] = k
# format message, split into list
message = message.split('/')
# decode message
decoded = []
for n in message:
decoded.append(alphabet_swapped[int(n)])
# return a string of the decoded message
return ''.join(decoded)
# use the cipher
def go():
# instructions
print("\n"*20)
print("Use this script to encode and decode messages with a simple numeric cipher.")
# get direction
while True:
direction = input("\nDo you want to encode or decode? (E/D) > ")
if not direction.lower() in ('e','d','encode','decode'):
print("Sorry, that's not a valid entry.")
continue
else:
if direction in ('e','encode'):
direction = 'encode'
else:
direction = 'decode'
break
# get the message
while True:
message = input("\nWhat is your secret message? > ")
if not len(message) > 0:
print("Sorry, that's not a valid message.")
continue
else:
break
# get the key
while True:
key = input("\nEnter a whole number to use as the cipher key > ")
try:
int(key)
except:
print("Sorry, that's not a valid whole number.")
continue
key = int(key)
break
# do it
if direction == 'encode':
print(f"\nEncoding message \"{message}\" using key \"{key}\"")
else:
print(f"\nDecoding message \"{message}\" using key \"{key}\"")
print("\nHere's your message:")
print(cipher(direction,key,message))
print("\n"*3)
go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment