Example #1
0
    def hack(self, encrypted: str) -> Union[str, None]:
        """Guess the key by finding the one with the minimal
        MSE wrt to the letter frequencies in the model.

        Arguments:
            encrypted {str} -- encrypted text

        Returns:
            Union[str, None] -- Decrypted text, or None if the decryption
            is impossible for some reason.
        """
        if self.model is None:
            print("No model provided. Exitting...")
            sys.exit()

        if not self.check_input_data(encrypted):
            return None

        mse = self.mse
        trained = self.model
        freqs_dict = self.model_instance.model_function
        alphabet = self.model_instance.alphabet

        errors = []
        for key in range(len(alphabet)):
            c1 = Caesar(key=key)
            try_freqs = freqs_dict(c1.decrypt(encrypted))
            errors.append(
                sum([mse(trained[l], try_freqs[l]) for l in alphabet]))

        min_error = min(errors)
        key = errors.index(min_error)
        c2 = Caesar(key=key)
        decrypted = c2.decrypt(encrypted)
        return decrypted
Example #2
0
File: cli.py Project: ssnd/ciphers
def decode(cipher: str, key: Union[int, str], input_file, output_file):
    """Use this command to decode the text (read from stdio or a file)
       using the available ciphers and display the decrypted text or write
       it to a file.
    """

    input_file_name = input_file.name if input_file is not None else None
    output_file_name = output_file.name if output_file is not None else None

    io_handler = IOHandler(input_file_name, output_file_name)

    input_text = io_handler.read()

    if cipher == "caesar":
        key = Caesar.check_key_type(key, int)
        c = Caesar(key=key)
        decrypted_str = c.decrypt(input_text)

    if cipher == "vigenere":
        v = Vigenere(key=key)
        decrypted_str = v.decrypt(input_text)

    if cipher == "vernam":
        if input_file is None:
            print(("An input file is required for the Vernam cipher"
                   " to work correctly. Exitting..."))
            sys.exit()
        vernam = Vernam(key=key)
        decrypted_str = vernam.decrypt(input_text)

    io_handler.write(decrypted_str)
Example #3
0
def caesar():
    if request.method == 'POST':
        key = int(request.form['key'])
        message = request.form['message']
        caesar = Caesar(message, key)
        user_option = request.form['option']

        if user_option == 'encrypt':
            new_message = caesar.encrypt()
        elif user_option == 'decrypt':
            new_message = caesar.decrypt()
        return render_template("caesar.html", new_message=new_message)

    return render_template("caesar.html")
Example #4
0
class caesarFrame(frameTemplate):
    def __init__(self):
        super().__init__()
        self.cs = Caesar()
        self.initUI()

    def initUI(self):
        super().initUI()

        self.definition.insertPlainText(caesar_txt)

        self.cb_method.addItem("Encrypt")
        self.cb_method.addItem("Decrypt")
        self.cb_method.currentIndexChanged.connect(self.selectionChange)

        regex = QtCore.QRegExp("^[a-zA-Z]+$")
        validator = QtGui.QRegExpValidator(regex, self.plaintext)
        self.plaintext.setValidator(validator)

        self.btn_encrypt.clicked.connect(self.encrypt)

    def selectionChange(self, index):
        self.btn_encrypt.clicked.disconnect()

        if (self.cb_method.itemText(index) == "Encrypt"):
            self.label_plaintext.setText("Plaintext:")
            self.label_ciphertext.setText("Ciphertext:")
            self.btn_encrypt.clicked.connect(self.encrypt)
            self.btn_encrypt.setText("Encrypt")
            self.plaintext.clear()
            self.ciphertext.clear()

        elif(self.cb_method.itemText(index) == "Decrypt"):
            self.label_plaintext.setText("Ciphertext:")
            self.label_ciphertext.setText("Plaintext:")
            self.btn_encrypt.clicked.connect(self.decrypt)
            self.btn_encrypt.setText("Decrypt")
            self.plaintext.clear()
            self.ciphertext.clear()

    def encrypt(self):
        text = self.cs.encrypt(self.plaintext.text())
        self.ciphertext.setText(text)

    def decrypt(self):
        text = self.cs.decrypt(self.plaintext.text())
        self.ciphertext.setText(text)
Example #5
0
# -*- coding: utf-8 -*-
import sys

sys.path.insert(0, '..')

from ciphers.caesar import Caesar

txt_in = input('Texto a ser codificado: ')
chave = input('Chave:')
if chave:
    chave = int(chave)
else:
    chave = 3
cifra = Caesar()
cifrado = cifra.encrypt(txt_in, chave)
print('Texto cifrado: ', cifrado)
print('  Texto plano: ', cifra.decrypt(cifrado, chave))
Example #6
0
def test_caesar_algorithm_dec():
    c = Caesar(key=1)
    assert c.decrypt("bcdø") == "abcø"
Example #7
0
def test_caesar_algorithm_dec_enc(a):
    c = Caesar(key=42)
    assert c.encrypt(c.decrypt(a)) == a