These examples are related to the notes: http://webbuild.knu.ac.kr/~mhs/classes/2019/spring/crypt/notes.pdf
There is a simple way to convert a character to and from its ASCII equivalent.
ord('F')
ord('A'), ord('Z'), ord('a'), ord('z'), ord(' ')
chr(70), chr(71), chr(231)
[(i,chr(i)) for i in range(90,97)]
But this will be a bit troublesome. Lets make our own encoding of a smaller alphabet.
myAlphabet = [chr(i) for i in range(65,91)];
myAlphabet.insert(0, chr(32)); myAlphabet.append(chr(46));
myAlphabet[5], myAlphabet.index('T')
Now lets make some nicely named functions for encoding and decoding.
def encode(lCharacter):
return myAlphabet.index(lCharacter);
def decode(lNumber):
return myAlphabet[lNumber];
decode(5); encode('Y');
Now we want to take a message, and convert it into a LIST of letters, so we can convert each to a number.
message = list('TOMORROW AT LUNCH.'); message
Yuck. I don't like reading it like that. I won't print out all of the lists from now on. Just a slice of them.
message = list('WHEN I FIND MYSELF IN TIMES OF TROUBLE MOTHER MARY COMES TO ME SPEAKING WORDS OF WISDOM LET IT BE.'); message[0:4]
Now lets ENCODE this to some simple numerical PLAINTEXT so that we can work with it.
plaintext = [encode(i) for i in message]; plaintext[0:5]
Or we could use the map function.
plaintext = map(encode, message); plaintext[0:5]
Now lets permute the numbers in our alphabet to make a simple substitiution cipher.
myPermutation=list(Permutations(26).random_element()); myPermutation[0:10]
myPermutation.insert(0, 0); myPermutation.append(27); myPermutation[0:10]
Notice I'm not permuting the space ' ' or the period '.'.
def encrypt(lNumber):
return myPermutation[lNumber];
def decrypt(lNumber):
return myPermutation.index(lNumber);
encrypt(10), decrypt(7), decrypt(encrypt(9))
codeword = map(encrypt, plaintext); codeword[0:10]
encrypt(27)
code = map(decode,codeword); code[0:10]
code = map(decode,map(encrypt, map(encode, list("I AM GOING TO KILL YOU")))); code[0:10]
Now. I don't want this as a list. I want it as a string.
def join(code):
message = ""
for i in range(len(code)):
message = message + code[i]
return message
join(code)
join(map(decode, map(decrypt, codeword)))
Lets package that all up into some convenient functions.
def MyEncrypt(plaintext):
return join(map(decode, map(encrypt, map(encode, list(plaintext)))))
cyphertext = MyEncrypt('WHO TOOK MY GUM.'); cyphertext
def MyDecrypt(cyphertext):
return join(map(decode, map(decrypt, map(encode, list(cyphertext)))))
MyDecrypt(cyphertext)