Anforderungsbeschreibung
Einleitung
Ist-Situation
Nachrichtentexte werden derzeit unverschlüsselt übertragen. Das soll geändert werden.
Soll-Situation
Es soll eine Konsolenanwendung entwickelt werden, mit der sich eine Zeichenkette nach der Caesar Verschlüsselung ver- und wieder entschlüsseln lässt. Die Größe der Verschiebung, sowie die Schieberichtung soll dabei variabel sein. Texte sind vor der Verschlüsselung in Großbuchstaben umzuwandeln.
Abgrenzung
Es sollen keine Ziffern und keine Sonderzeichen verschlüsselt werden. Die Verschlüsselung soll auf die Großbuchstaben des Alphabets beschränkt werden.
Meilensteine
Meilenstein 1
- Texte verschlüsseln abgeschlossen
Meilenstein 2
- Texte entschlüsseln abgeschlossen
Beispielcode
base_encrypter.py
class BaseEncrypter:
def encrypt(self):
pass
def decrypt(self):
pass
caesar.py
from base_encrypter import BaseEncrypter
class Caesar(BaseEncrypter):
def __init__(self, shift, direction):
self.shift = shift
self.direction = direction
def encrypt(self, text=""):
"""Encrypts the given text based on the number of characters to shift and the direction."""
result = ""
# loop through all characters in the string
for c in text.upper():
# get the ascii code of the character
ascii_code = ord(c)
# check, if ascii code is within range
if ord("A") <= ascii_code <= ord("Z"):
# check direction of the character shift
if self.direction == 1:
ascii_code += self.shift
else:
ascii_code -= self.shift
# wrap around necessary?
ascii_code = self.__wrap_around(ascii_code)
# add the encrypted character to the result
result += chr(ascii_code)
# return the result
return result
def decrypt(self, text=""):
"""Decrypts the given text based on the number of characters to shift and the direction."""
result = ""
# loop through all characters in the string
for c in text.upper():
# get the ascii code of the character
ascii_code = ord(c)
# check, if ascii code is within range
if ord("A") <= ascii_code <= ord("Z"):
# check direction of the character shift
if self.direction == 1:
ascii_code -= self.shift
else:
ascii_code += self.shift
# wrap around necessary?
ascii_code = self.__wrap_around(ascii_code)
# add the decrypted character to the result
result += chr(ascii_code)
# return the result
return result
def __wrap_around(self, ascii_code=0):
"""Checks whether or not the ascii_code is out of range. Wraps the ascii_code around, if it is out of range."""
# ascii_code less than "A" -> wrap around to "Z"
if ord("A") > ascii_code >= ord("A") - self.shift:
i = ord("A") - ascii_code
return ord("Z") + 1 - i
# ascii_code greater than "Z" -> wrap around to "A"
if ord("Z") < ascii_code <= ord("Z") + self.shift:
i = ascii_code - ord("Z")
return ord("A") - 1 + i
# ignore special characters (i.e. Space, !, ., etc.
return ascii_code
main.py
from caesar import Caesar
def main():
caesar = Caesar(5, 1)
enc = caesar.encrypt("Hello World!")
print(enc)
print(caesar.decrypt(enc))
if __name__ == "__main__":
main()