I have a dictionary which I use to lookup my binary and ASCII values (from A - P). It works, but my ascii2bin
function just doesn't really feel right (and beautiful). Is there is a better way to write it?
The ascii2bin
function splits a 2-letter string (i.e. 'LA') and looks up the keys in the dictionary. Then concatenates the 2 keys to each other to get an 8bit string.
Check the comment for the assignment which was given.
import sdes
"""
Using S-DES, decrypt the string (10100010) using the key (0111111101) by hand.
Then decode the 4 bits of the plaintext string to a letter and the second 4 bits to another letter where
we encode A through P in base 2 (i.e., A = 0000, B = 0001, ..., P = 1111).
"""
KEY = '0111111101'
CIPHERTEXT = '10100010'
ALPHABET = {'0000': 'A',
'0001': 'B',
'0010': 'C',
'0011': 'D',
'0100': 'E',
'0101': 'F',
'0110': 'G',
'0111': 'H',
'1000': 'I',
'1001': 'J',
'1010': 'K',
'1011': 'L',
'1100': 'M',
'1101': 'N',
'1110': 'O',
'1111': 'P'}
def bin2ascii(bin):
return ALPHABET[bin[:4]] + ALPHABET[bin[4:]]
def ascii2bin(string_of_2_letters):
bits = []
for i in range(0, 2):
bits += ([key for key, val in ALPHABET.items() if val == string_of_2_letters[i]])
return bits[0] + bits[1]
print bin2ascii(sdes.decrypt(CIPHERTEXT, KEY))