2021-10-15 15:25:08 +00:00
|
|
|
import random
|
|
|
|
|
|
|
|
from utils import AlphabetUtils as au
|
|
|
|
|
|
|
|
|
|
|
|
def encrypt_text(cleartext: str, key: [int]):
|
|
|
|
"""
|
|
|
|
Encrypts the given text with the given key
|
|
|
|
:param cleartext: The text to encrypt
|
|
|
|
:param key: The key to use. Has to be a list of indices of the alphabet, so [0...25] shuffled
|
|
|
|
:return: The encrypted text
|
|
|
|
"""
|
|
|
|
resulting = ''
|
|
|
|
|
|
|
|
for char in cleartext:
|
|
|
|
charIndex = au.get_index_of_letter(char)
|
|
|
|
cipherIndex = key.index(charIndex)
|
|
|
|
cipherChar = au.get_letter_at_index(cipherIndex)
|
|
|
|
resulting += cipherChar
|
|
|
|
|
|
|
|
return resulting
|
|
|
|
|
|
|
|
|
|
|
|
def decrypt_text(ciphertext: str, key: [int]):
|
|
|
|
"""
|
|
|
|
Decrypts the given ciphertext with the given key
|
|
|
|
:param ciphertext: The text to decrypt
|
|
|
|
:param key: The key to use. Has to be a list of indices of the alphabet, so [0...25] shuffled
|
|
|
|
:return: The decrypted text
|
|
|
|
"""
|
|
|
|
resulting = ''
|
|
|
|
|
|
|
|
for char in ciphertext:
|
|
|
|
charIndex = au.get_index_of_letter(char)
|
|
|
|
clearIndex = key[charIndex]
|
|
|
|
clearChar = au.get_letter_at_index(clearIndex)
|
|
|
|
resulting += clearChar
|
|
|
|
|
|
|
|
return resulting
|
|
|
|
|
|
|
|
|
2021-10-15 15:55:16 +00:00
|
|
|
def generate_key():
|
|
|
|
"""
|
|
|
|
Generates a key that can be used for this cipher.
|
|
|
|
:return: The key as a list of indices
|
|
|
|
"""
|
2021-10-15 15:25:08 +00:00
|
|
|
indices = [i for i in range(26)]
|
|
|
|
|
|
|
|
random.shuffle(indices)
|
|
|
|
|
|
|
|
return indices
|
|
|
|
|
2021-10-15 15:55:16 +00:00
|
|
|
def generate_key_with_keyword(keyword: str):
|
|
|
|
result = []
|
|
|
|
|
|
|
|
for char in keyword:
|
|
|
|
charIndex = au.get_index_of_letter(char)
|
|
|
|
if charIndex not in result:
|
|
|
|
result.append(charIndex)
|
|
|
|
|
|
|
|
remainingIndices = [i for i in range(26-len(result))]
|
|
|
|
|
|
|
|
result.extend(remainingIndices)
|
|
|
|
|
|
|
|
return result
|
2021-10-15 15:25:08 +00:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2021-10-15 15:55:16 +00:00
|
|
|
key = generate_key_with_keyword('patrick')
|
2021-10-15 15:25:08 +00:00
|
|
|
print(key)
|
|
|
|
encrypted = encrypt_text('BonkRocks', key)
|
|
|
|
print(encrypted)
|
|
|
|
print(decrypt_text(encrypted, key))
|