Last active
December 23, 2022 17:42
-
-
Save hosteren/852202caffa5fa88b317689ff6ea5be8 to your computer and use it in GitHub Desktop.
A simple Caesar Cipher class in Python with a bruteforce function (a SetFit model)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import string | |
from setfit import SetFitModel | |
class Caesar: | |
"""My name is Julius and I'm here to say, | |
jhwwlqj vwdeehg zloo nhhs olih dw edb""" | |
def __init__(self, lang = "en") -> None: | |
# Bilingual appalicious | |
self.alphabets = { | |
"en": string.ascii_lowercase, | |
"da": f"{string.ascii_lowercase}æøå", | |
} | |
self.spaces = " -_!?:;=.,~'*\"\n\t" | |
self.alphabet = self.alphabets[lang] | |
self.alphabet_list = [*self.alphabet] | |
def _generate_alphabet(self, key: int) -> dict: | |
# "Ordbogen" der tager et tal som nøgle | |
# så en anden funktion kan gøre alt det hårde arbejde. | |
# Typisk.. | |
first_split = self.alphabet[:key] | |
second_split = self.alphabet[key:] | |
alphabet = f"{second_split}{first_split}" | |
alphabet_list = [*alphabet] | |
alphabet_dict = {} | |
for idx in range(len(self.alphabet_list)): | |
orig_char = self.alphabet_list[idx] | |
alphabet_dict[orig_char] = alphabet_list[idx] | |
return alphabet_dict | |
def _shift(self, alphabet: dict, text: str) -> str: | |
# Alle pattedyr har potentialet for genialitet. | |
# I forhold til det kvantemekaniske mirakel der foregår her.. | |
# I mean.. ARMA GENUS! | |
result = "" | |
for char in text: | |
is_upper = None | |
if char.isupper(): | |
is_upper = True | |
char = char.lower() | |
if char in self.spaces: | |
result = f"{result}{char}" | |
if char in self.alphabet: | |
new_char = alphabet[char] | |
if is_upper: | |
new_char = new_char.upper() | |
result = f"{result}{new_char}" | |
return result | |
def encrypt(self, text: str, key: int) -> str: | |
# Uwkyå zvt | |
alphabet_dict = self._generate_alphabet(key) | |
result = self._shift(alphabet_dict, text) | |
return result | |
def decrypt(self, text: str, key: int) -> str: | |
alphanet_dict = self._generate_alphabet(key) | |
alphanet_dict = {v: k for k, v in alphanet_dict.items()} # UNO reverso | |
result = self._shift(alphanet_dict, text) | |
return result | |
def bruteforce_decrypt(self, text: str) -> dict: | |
# Vent lige, Morphie Fiskebrand. Er det ikke en afledningsmanøvre lige bag dig? *haps haps* | |
# Catch you on the flip flop, dingelings! | |
detector = SetFitModel.from_pretrained("trollek/setfit-gibberish-detector") | |
results = [] | |
for idx in range(len(self.alphabet_list)): | |
bf_text = self.decrypt(text.lower(), idx) | |
if detector.predict(bf_text) == 0: | |
results.append({idx: bf_text}) | |
return results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment