Create a dictionary using two alphabets with the letters of one alphabet assigned randomly to the letters of the other. This is the key, which can be exported as a file (using ipython magic in this case).
To encipher, create a random alphabet map 1:1
from random import shuffle
alphabet = {chr(num):chr(num) for num in range(97,123)}
values = alphabet.values()
shuffle(values)
random_substitution = dict(zip(alphabet.keys(), values))
print random_substitution
print "now export key to file"
Gives something like:
{‘a’: ‘u’, ‘c’: ‘d’, ‘b’: ‘b’, ‘e’: ‘p’, ‘d’: ‘n’, ‘g’: ‘v’, ‘f’: ‘m’, ‘i’: ‘f’, ‘h’: ‘i’, ‘k’: ‘k’, ‘j’: ‘e’, ‘m’: ‘s’, ‘l’: ‘x’, ‘o’: ‘q’, ‘n’: ‘c’, ‘q’: ‘l’, ‘p’: ‘r’, ‘s’: ‘z’, ‘r’: ‘y’, ‘u’: ‘w’, ‘t’: ‘t’, ‘w’: ‘h’, ‘v’: ‘j’, ‘y’: ‘g’, ‘x’: ‘o’, ‘z’: ‘a’}
now export key to file
%%writefile C:/Users/HP/Desktop/key.txt
0
#Write key to file
f = open('C:/Users/HP/Desktop/key.txt', 'w' )
f.write(repr(random_substitution) + '\n' )
f.close()
Using key, perform substitution. Remove spaces…
plaintext = raw_input("enter plaintext: ")
plaintext = plaintext.lower()
plaintext = plaintext.replace(" ", "")
print plaintext
gives:
enter plaintext: hello world
helloworld
ciphertext = ''
for letter in plaintext:
substitution = random_substitution[letter]
ciphertext = ciphertext+substitution
print "ciphertext is: ",ciphertext
gives:
ciphertext is: ipxxqhqyxn
To decipher, open key file, it’s a string so parse it back into a (python) dictionary, then input ciphertext.
f = open('C:/Users/HP/Desktop/key.txt')
z = f.read()
y = z[1:-2]
i = 0
j = 8
keys_import = {}
while j <=258:
z = y[i:j]
key = z[1:2]
value = z[6:7]
keys_import[key] = value
i = j + 2
j = j + 10
print keys_import
ciphertext = raw_input("insert ciphertext: ")
Then swap the values and keys to get plaintext back:
k = keys_import.keys()
v = keys_import.values()
x = zip(v, k)
x = dict(x)
plaintext_back = ''
for letter in ciphertext:
substitution_back = x[letter]
plaintext_back = plaintext_back+substitution_back
print "plaintext is: ",plaintext_back
gives:
plaintext is: helloworld