♻️ Moved shifting function to utils

This commit is contained in:
David Huh 2021-10-18 14:19:29 +02:00
parent fbf2c08ff7
commit 5fd431cef1
2 changed files with 84 additions and 79 deletions

View File

@ -1,3 +1,6 @@
from utils import CipherUtils
def encrypt_text(cleartext: str = 'Bitcoin', incrementation: int = 13): def encrypt_text(cleartext: str = 'Bitcoin', incrementation: int = 13):
""" """
This method encrypts a text by shifting each letter by the value of incrementation This method encrypts a text by shifting each letter by the value of incrementation
@ -30,28 +33,11 @@ def shift_text(cleartext: str, incrementation: int):
shifted_text = '' shifted_text = ''
for char in cleartext: for char in cleartext:
shifted_text += increment_char(char, incrementation) shifted_text += CipherUtils.shift_char(char, incrementation)
return shifted_text return shifted_text
def increment_char(char, incrementation: int = 1):
"""
This method shifts one char by the value of incrementation
:param char: Char to be shifted
:param incrementation: How much the char should be shifted
:return: Shifted letter
"""
# converting character to byte
char_in_bytes = bytes(char, 'utf-8')[0]
if char_in_bytes + incrementation >= 91 and char_in_bytes < 91 \
or char_in_bytes + incrementation >= 123: # z -> 122 | 90 -> Z so go backwards
new_char_in_bytes = bytes([char_in_bytes - (26 - incrementation)])
else:
new_char_in_bytes = bytes([char_in_bytes + incrementation])
return str(new_char_in_bytes)[2]
def brute_force_example(cleartext: str = 'Bitcoin', incrementation: int = 7): def brute_force_example(cleartext: str = 'Bitcoin', incrementation: int = 7):

View File

@ -27,7 +27,7 @@ GERMAN_FREQUENCY_PROFILE = [
0.0003, 0.0003,
0.0004, 0.0004,
0.0113 0.0113
] ]
def calculate_frequency(text: str, fancy_printing: bool = False): def calculate_frequency(text: str, fancy_printing: bool = False):
@ -74,6 +74,25 @@ def transform_invalid_chars(input: str) -> str:
return res return res
def shift_char(char, incrementation: int = 1):
"""
This method shifts one char by the value of incrementation
:param char: Char to be shifted
:param incrementation: How much the char should be shifted
:return: Shifted letter
"""
# converting character to byte
char_in_bytes = bytes(char, 'utf-8')[0]
if char_in_bytes + incrementation >= 91 and char_in_bytes < 91 \
or char_in_bytes + incrementation >= 123: # z -> 122 | 90 -> Z so go backwards
new_char_in_bytes = bytes([char_in_bytes - (26 - incrementation)])
else:
new_char_in_bytes = bytes([char_in_bytes + incrementation])
return str(new_char_in_bytes)[2]
if __name__ == '__main__': if __name__ == '__main__':
print( print(
calculate_frequency('Hier den Text eingeben, für den die Wahrscheinlichkeiten berechnet werden sollen', True)) calculate_frequency('Hier den Text eingeben, für den die Wahrscheinlichkeiten berechnet werden sollen', True))