|
| 1 | +class BaconCipher: |
| 2 | + def __init__(self) -> None: |
| 3 | + self.baco_dict = { |
| 4 | + 'A':'aaaaa', 'B':'aaaab', 'C':'aaaba', |
| 5 | + 'D':'aaabb', 'E':'aabaa', 'F':'aabab', |
| 6 | + 'G':'aabba', 'H':'aabbb', 'I':'abaaa', |
| 7 | + 'J':'abaab', 'K':'ababa', 'L':'ababb', |
| 8 | + 'M':'abbaa', 'N':'abbab', 'O':'abbba', |
| 9 | + 'P':'abbbb', 'Q':'baaaa', 'R':'baaab', |
| 10 | + 'S':'baaba', 'T':'baabb', 'U':'babaa', |
| 11 | + 'V':'babab', 'W':'babba', 'X':'babbb', |
| 12 | + 'Y':'bbaaa', 'Z':'bbaab' |
| 13 | + } |
| 14 | + self.reverse_baco = { |
| 15 | + self.baco_dict[key] : key for key in self.baco_dict } |
| 16 | + |
| 17 | + def encrypt(self, message : str) -> str: |
| 18 | + cipher = '' |
| 19 | + for letter in message.upper(): |
| 20 | + # checks for space |
| 21 | + if(letter != ' '): |
| 22 | + # adds the ciphertext corresponding to the |
| 23 | + # plaintext from the dictionary |
| 24 | + cipher += self.baco_dict[letter] |
| 25 | + else: |
| 26 | + # adds space |
| 27 | + cipher += ' ' |
| 28 | + return cipher |
| 29 | + |
| 30 | + def decrypt(self,message): |
| 31 | + decipher = '' |
| 32 | + i = 0 |
| 33 | + while True : |
| 34 | + if(i < len(message)-4): |
| 35 | + # extracting a set of ciphertext |
| 36 | + # from the message which is of size 5 |
| 37 | + substr = message[i:i + 5] |
| 38 | + # checking for space as the first |
| 39 | + # character of the substring |
| 40 | + if(substr[0] != ' '): |
| 41 | + decipher += self.reverse_baco[substr] |
| 42 | + i += 5 # to get the next set of ciphertext |
| 43 | + else: |
| 44 | + # adds space |
| 45 | + decipher += ' ' |
| 46 | + i += 1 # index next to the space |
| 47 | + else: |
| 48 | + break |
| 49 | + return decipher |
0 commit comments