...
 
Commits (3)
#!/usr/bin/env python3
"""
Huffman-Kodierung
MIT License
Copyright (C) 2019 Linus Jahn <lnj@kaidan.im>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from HuffmanNode import HuffmanNode
"""
Ueberfuehrt einen Text in eine sortierte Liste von HuffmanNodeen
"""
class HK_Liste(object):
"""
Der Konstruktor legt die Attribute an:
* Text
* Liste
"""
def __init__(self, text: str = ""):
self.text = text
self.liste = []
self.__textAnalysieren()
self.__sortieren()
self.__buildTree()
"""
Liefert die Liste als String zurueck.
"""
def __str__(self) -> str:
output = "["
listLen = len(self.liste)
for i in range(listLen):
output += str(self.liste[i])
if i < listLen - 1:
output += ", "
output += "]"
return output
"""
Gibt die Laenge der Liste zurueck.
"""
def __len__(self) -> int:
return len(self.liste)
"""
Analysiert eine Texteingabe und fügt HuffmanNodee für jeden Buchstaben in
@c liste hinzu.
"""
def __textAnalysieren(self):
for char in self.text:
self.__textHinzu(char)
def __buildTree(self):
while len(self) > 1:
lastTwo = self.pop2()
newElement = lastTwo[0] + lastTwo[1]
self.push(newElement)
self.__sortieren()
"""
Ergaenzt die Liste um ein weiteres Element, oder, falls der Text schon
erfasst wurde, erhoeht dessen Gewicht.
"""
def __textHinzu(self, char: str):
for item in self.liste:
if item.text == char:
item.gewicht += 1
return
self.push(HuffmanNode(char))
"""
Sortiert die Liste gemaess ihrer Gewichte.
"""
def __sortieren(self):
self.liste.sort(reverse = True)
"""
Entfernt das letzte Element aus der Liste und gibt es zurueck.
"""
def pop(self) -> HuffmanNode:
return self.liste.pop()
"""
Entfernt die letzten zwei Element aus der Liste und gibt sie zurueck.
"""
def pop2(self) -> list:
return [self.pop(), self.pop()]
"""
Ergaenzt die Liste um ein weiteres HuffmanNode und sortiert die Liste.
"""
def push(self, tg: HuffmanNode):
self.liste.append(tg)
self.__sortieren()
def encode(self, input) -> str:
output = ""
for char in input:
tg = self.liste[0]
done = False
path = ""
while not done:
if not char in tg.text:
return "Encoding failed: invalid char ({}).".format(char)
if char == tg.text:
output += path # + " "
done = True
else:
if char in tg.children[0].text:
path += "0"
tg = tg.children[0]
else:
path += "1"
tg = tg.children[1]
return output
def decode(self, input: str) -> str:
if not input or not self.liste:
return
output = ""
node = self.liste[0]
for char in input:
if char == "0":
node = node.children[0]
else:
node = node.children[1]
if not node.children:
output += node.text
node = self.liste[0]
return output
def encodeStats(self, text: str):
huffSize: int = len(self.encode(text))
print("Huffman-Kodierung spart {}%".format(1 - (huffSize / (len(text) * 8))))
def encode(input):
hkliste = HK_Liste(input)
print(hkliste.encode(input))
hkliste.encodeStats(input)
if __name__ == "__main__":
tgl = HK_Liste("REISSIG")
print(tgl.decode("0001111101011010"))
#print(tgl)
#print(tgl.encode("REISSIG"))
encode("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV")
......@@ -28,68 +28,27 @@ SOFTWARE.
import sys
class Textgewicht(object):
class HuffmanNode(object):
def __init__(self, text: str, gewicht: int = 1):
self.text = text
self.gewicht = gewicht
self.children = []
def __add__(self, other):
if self.text == other.text:
return Textgewicht(self.text, self.gewicht + other.gewicht)
tg = HuffmanNode(self.text, self.gewicht + other.gewicht)
else:
tg = HuffmanNode(self.text + other.text, self.gewicht + other.gewicht)
tg.children = [self, other]
return Textgewicht(self.text + other.text,
self.gewicht + other.gewicht)
return tg
def __str__(self):
return "{} ({})".format(self.text, self.gewicht)
def __str__(self) -> str:
return "'{}' ({})".format(self.text, self.gewicht)
def __lt__(self, other):
def __lt__(self, other) -> bool:
return self.gewicht < other.gewicht
class TGListe(object):
def __init__(self):
self.liste = []
def __str__(self):
output = "["
listLen = len(self.liste)
for i in range(listLen):
output += str(self.liste[i])
if i < listLen - 1:
output += ", "
output += "]"
return output
def __addChar(self, char: str):
if self.liste:
for item in self.liste:
if item.text == char:
item.gewicht += 1
return
# Maybe use desc sorting order?
self.liste.append(Textgewicht(char))
def __sort(self):
self.liste = sorted(self.liste)
"""
Analysiert eine Texteingabe und fügt Textgewichte für jeden Buchstaben in
@c liste hinzu.
@note Die Methode kann mehrmals aufgerufen werden, löscht dabei aber nicht
den bestehenden Datensatz.
@param input Eingabe, die analysiert werden soll.
"""
def analyze(self, input: str):
for char in input:
self.__addChar(char)
self.__sort()
def printUsage():
print("Usage: " + sys.argv[0] + " [input]")
......
#!/usr/bin/env python3
import sys
from PySide2.QtCore import QObject, Signal, Slot, Property, QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_=-+{}[]\"|\'/?.>,<~` ÄÜÖäüö°^°âêôẑûî"
class Backend(QObject):
def __init__(self):
QObject.__init__(self)
@staticmethod
def translate(input, key, encrypt = True):
if not input or not key:
return ""
i = 0
output = ""
for c in input:
if encrypt:
output += ALPHABET[(ALPHABET.index(c) + ALPHABET.index(key[i])) % len(ALPHABET)]
else:
output += ALPHABET[(ALPHABET.index(c) - ALPHABET.index(key[i])) % len(ALPHABET)]
i = (i + 1) % len(key)
return output
@Slot(str, str)
def encrypt(self, message, key):
return self.translate(message, key)
@Slot(str, str)
def decrypt(self, cipher, key):
return self.translate(cipher, key, encrypt = False)
#self.inputVal = ""
#self.keyVal = ""
#self.resultVal = ""
#self.encrypt = True
#def getInput(self) -> str:
#return self.inputVal
#def setInput(self, input: str):
#self.inputVal = input
#self.inputChanged.emit()
#def getKey(self) -> str:
#return self.keyVal
#def setKey(self, key: str):
#self.keyVal = key
#self.keyChanged.emit()
#def getEncrypt(self) -> bool:
#return self.encryptVal
#def setEncrypt(self, encrypt: bool):
#self.encryptVal = encrypt
#self.encryptChanged.emit()
#def getResult(self) -> str:
#return self.resultVal
#def setResult(self, result: str):
#self.resultVal = result
#self.resultChanged.emit()
#inputChanged = Signal()
#input = Property(str, getInput, setInput, notify=inputChanged)
#keyChanged = Signal()
#key = Property(str, getKey, setKey, notify=keyChanged)
#encryptChanged = Signal()
#encrypt = Property(bool, getEncrypt, setEncrypt, notify=encryptChanged)
#resultChanged = Signal()
#result = Property(str, getResult, setResult, notify=resultChanged)
if __name__ == "__main__":
backend = Backend()
app = QGuiApplication(sys.argv);
engine = QQmlApplicationEngine();
engine.rootContext().setContextProperty("backend", backend);
engine.load("main.qml");
sys.exit(app.exec_());
import QtQuick 2
import QtQuick.Controls 2 as Controls
import QtQuick.Layouts 1
Controls.ApplicationWindow {
visible: true
Column {
// leftPadding: 5
// rightPadding: 5
// topPadding: 5
// bottomPadding: 5
anchors.fill: parent
Controls.Switch {
id: encryptSwitch
}
Controls.Label {
text: "Eingabe:"
}
Controls.TextArea {
id: inputField
width: 500
height: 100
text: backend.input
}
Controls.Label {
text: "Schlüssel:"
}
Controls.TextField {
id: keyField
text: backend.key
}
Controls.Label {
text: "Ausgabe:"
}
Controls.Label {
text: {
if (encryptSwitch.checked) {
return backend.encrypt(inputField.text, keyField.text);
} else {
return backend.decrypt(inputField.text, keyField.text);
}
}
}
}
}
#!/usr/bin/env python3
"""
Vigene-Verschluesselung
MIT License
Copyright (C) 2019 Linus Jahn <lnj@kaidan.im>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import tkinter as tk
from vigenere import Vigenere
class VigenereApplication(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.buildWindow()
self.model = Vigenere()
def buildWindow(self):
tk.Label(self, text="Eingabe:").pack()
self.inputField = tk.Text(self)
self.inputField.pack()
tk.Label(self, text="Schluessel:").pack()
self.keyField = tk.Entry(self)
self.keyField.pack()
self.encryptVar = tk.IntVar()
tk.Radiobutton(self,
text = "Verschluesseln",
command = self.updateOutput,
variable = self.encryptVar,
value = 1).pack()
tk.Radiobutton(self,
text = "Entschlueseln",
variable = self.encryptVar,
value = 0,
command = self.updateOutput).pack()
tk.Button(self,
text="Verschluesseln/Entschluesseln",
command=self.updateOutput).pack()
tk.Label(self, text="Ausgabe:").pack()
self.outputVar = tk.StringVar()
self.outputLabel = tk.Message(self, textvariable=self.outputVar, width=80)
self.outputLabel.pack()
def updateOutput(self):
msg = self.inputField.get("1.0", "end-1c")
key = self.keyField.get()
output = self.model.translate(msg, key, bool(self.encryptVar.get()))
self.outputVar.set(output)
if __name__ == "__main__":
root = tk.Tk()
app = VigenereApplication(master=root)
app.mainloop()
#!/usr/bin/env python3
"""
Vigene-Verschluesselung
MIT License
Copyright (C) 2019 Linus Jahn <lnj@kaidan.im>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_=-+{}[]\"|\'/?.>,<~` ÄÜÖäüö°^°âêôẑûî"
class Vigenere:
def translate(self, input, key, encrypt = True):
i = 0
output = ""
for c in input:
if encrypt:
output += ALPHABET[(ALPHABET.index(c) + ALPHABET.index(key[i])) % len(ALPHABET)]
else:
output += ALPHABET[(ALPHABET.index(c) - ALPHABET.index(key[i])) % len(ALPHABET)]
i = (i + 1) % len(key)
return output
def encrypt(self, message, key):
return self.translate(message, key)
def decrypt(self, cipher, key):
return self.translate(cipher, key, encrypt = False)
if __name__ == "__main__":
print(encrypt("1234", "Hallo"))
print(encrypt("Guten Tag, mein Name ist Marcel Davis und wir gehen erst wieder, wenn der Anschluss läuft!", "Ich habe einen SEHR guhten Schlüssel GeAählt111!!t!TT!1elf"))
print(decrypt("SGFWEEOMQ", "KEY"))