Krypto_Grundlagen/chapter_one/Permutations-Chiffre.py

75 lines
1.7 KiB
Python

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:
char_index = au.get_index_of_letter(char)
cipher_index = key.index(char_index)
cipher_char = au.get_letter_at_index(cipher_index)
resulting += cipher_char
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:
char_index = au.get_index_of_letter(char)
clear_index = key[char_index]
clear_char = au.get_letter_at_index(clear_index)
resulting += clear_char
return resulting
def generate_key():
"""
Generates a key that can be used for this cipher.
:return: The key as a list of indices
"""
indices = [i for i in range(26)]
random.shuffle(indices)
return indices
def generate_key_with_keyword(keyword: str):
result = []
for char in keyword:
char_index = au.get_index_of_letter(char)
if char_index not in result:
result.append(char_index)
remaining_indices = [i for i in range(26 - len(result))]
result.extend(remaining_indices)
return result
if __name__ == '__main__':
key = generate_key_with_keyword('patrick')
print(key)
encrypted = encrypt_text('BonkRocks', key)
print(encrypted)
print(decrypt_text(encrypted, key))