コード例 #1
0
ファイル: cli.py プロジェクト: 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)
コード例 #2
0
    def test_caesar(self):
        caesar = Caesar()
        encoded_phrase = caesar.encode(self.phrase)
        decoded_phrase = caesar.decode(encoded_phrase)
        print('Caesar: {0} => {1} => {2}'.format(self.phrase, encoded_phrase, decoded_phrase))

        self.assertEqual(decoded_phrase, self.phrase)
コード例 #3
0
 def decode(self, text, cipher_key):
     """Use decode from Caesar, then Multiplication"""
     caesar = Caesar()
     decoded_text = caesar.decode(text, cipher_key[1])
     multiplication = Multiplication()
     decoded_text = multiplication.decode(decoded_text, cipher_key[0])
     return decoded_text
コード例 #4
0
ファイル: unbreakable.py プロジェクト: stianbm/tdt4113
 def encode(self, text, cipher_key):
     """Use keyword to shift characters by using Caesar"""
     encoded_text = ''
     caesar = Caesar()
     for i in range(0, len(text)):
         encoded_text += caesar.encode(text[i],
                                       ord(cipher_key[(i % len(cipher_key))]))
     return encoded_text
コード例 #5
0
 def encode(self, text, cipher_key):
     """Use Multiplication, then Caesar"""
     multiplication = Multiplication()
     encoded_text = multiplication.encode(text, cipher_key[0])
     print('Multiplied: ', encoded_text)
     caesar = Caesar()
     encoded_text = caesar.encode(encoded_text, cipher_key[1])
     print('Caesared: ', encoded_text)
     return encoded_text
コード例 #6
0
 def possible_keys(self):
     caesar = Caesar()
     multiplication = Multiplication()
     multiplication_keys = multiplication.possible_keys()
     caesar_keys = caesar.possible_keys()
     keys = []
     for key in multiplication_keys:
         for c_key in caesar_keys:
             keys.append((key, c_key))
     return keys
コード例 #7
0
def main():
    """Main function to be run"""

    test_ciphers()

    text = 'ENCODED'
    key = 3
    caesar = Caesar()

    sender = Sender(key, caesar)
    receiver = Receiver(key, caesar)
    encoded = sender.operate_cipher(text)
    receiver.operate_cipher(encoded)
    hacker = Hacker(caesar.possible_keys(), caesar)
    hacker.operate_cipher(encoded)
    print()

    multiplication = Multiplication()
    sender.set_cipher_algorithm(multiplication)
    receiver.set_cipher_algorithm(multiplication)
    encoded = sender.operate_cipher(text)
    receiver.operate_cipher(encoded)
    hacker.set_cipher_algorithm(multiplication)
    hacker.operate_cipher(encoded)
    print()

    affine = Affine()
    sender.set_cipher_algorithm(affine)
    receiver.set_cipher_algorithm(affine)
    key = (3, 3)
    sender.set_cipher_key(key)
    receiver.set_cipher_key(key)
    encoded = sender.operate_cipher(text)
    receiver.operate_cipher(encoded)
    hacker.set_cipher_key(affine.possible_keys())
    hacker.set_cipher_algorithm(affine)
    hacker.operate_cipher(encoded)
    print()

    unbreakable = Unbreakable()
    key = 'ABIDE'
    sender.set_cipher_algorithm(unbreakable)
    receiver.set_cipher_algorithm(unbreakable)
    sender.set_cipher_key(key)
    receiver.set_cipher_key(key)
    encoded = sender.operate_cipher(text)
    receiver.operate_cipher(encoded)
    hacker.set_cipher_algorithm(unbreakable)
    #hacker.set_cipher_key(unbreakable.possible_keys())
    #hacker.operate_cipher(encoded)
    hacker.crack_unbreakable(encoded)
コード例 #8
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")
コード例 #9
0
ファイル: caesar_gui.py プロジェクト: pvinicki/CryptoSys
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)
コード例 #10
0
ファイル: main.py プロジェクト: matthewgrzegorczyk/BSK
def do_option(option: int, mode_option: int, text: str, key: str):
    result = ''

    if option == 1:
        rail_fence = RailFence(int(key))

        if mode_option == 1:
            result = rail_fence.encode(text)
        else:
            result = rail_fence.decode(text)

    elif option == 2:
        viegnere = Viegnere()

        if mode_option == 1:
            result = viegnere.encode(text, key)
        else:
            result = viegnere.decode(text, key)

    elif option == 3:
        matrix = Matrix(key)

        if mode_option == 1:
            result = matrix.encode(text)
        else:
            result = matrix.decode(text)

    elif option == 4:
        caesar = Caesar(int(key))

        if mode_option == 1:
            result = caesar.encode(text)
        else:
            result = caesar.decode(text)

    else:
        print("Zla opcja!")

    if result != '':
        if mode_option == 1:
            print("Zaszyfrowany tekst: {}".format(result))
        else:
            print("Odszyfrowany tekst: {}".format(result))

    return
コード例 #11
0
ファイル: hack_caesar.py プロジェクト: ssnd/ciphers
    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
コード例 #12
0
def test_ciphers():
    """Runs verify of ciphers"""
    text = 'ENCODED'
    key = 15
    caesar = Caesar()
    caesar.verify(text, key)

    multiplication = Multiplication()
    key = multiplication.generate_keys()
    multiplication.verify(text, key)

    affine = Affine()
    key = (multiplication.generate_keys(), 5)
    print('Key: ', key)
    affine.verify(text, key)

    unbreakable = Unbreakable()
    key = 'PIZZA'
    unbreakable.verify(text, key)

    rsa = RSA()
    public_key, private_key = rsa.generate_keys()
    rsa.verify(text, (public_key, private_key))
コード例 #13
0
def test_caesar_algorithm_enc():
    c = Caesar(key=1)
    assert c.encrypt("abc\n") == "bcd\n"
コード例 #14
0

def write_file(name, string):
    file = open(name, 'w')
    file.write(string)
    file.close()


print('Encrypting files...')

plain_list = read_file('caesar_plain.txt')
output = ''
for key in [3, 6, 12]:
    output += 'Key = ' + str(key) + '\n'
    for plain in plain_list:
        caesar = Caesar(plain, key)
        output += caesar.encrypt() + '\n'
    output += '\n'
write_file('caesar_cipher.txt', output)

plain_list = read_file('playfair_plain.txt')
output = ''
for key in ['rats', 'archangel']:
    output += 'Key = ' + key + '\n'
    for plain in plain_list:
        playfair = Playfair(plain, key)
        output += playfair.encrypt() + '\n'
    output += '\n'
write_file('playfair_cipher.txt', output)

plain_list = read_file('hill_plain_2x2.txt')
コード例 #15
0
ファイル: caesar_gui.py プロジェクト: pvinicki/CryptoSys
 def __init__(self):
     super().__init__()
     self.cs = Caesar()
     self.initUI()
コード例 #16
0
def test_caesar_algorithm_dec_enc(a):
    c = Caesar(key=42)
    assert c.encrypt(c.decrypt(a)) == a
コード例 #17
0
def test_caesar_algorithm_dec():
    c = Caesar(key=1)
    assert c.decrypt("bcdø") == "abcø"
コード例 #18
0
ファイル: test_caesar.py プロジェクト: fabmedeiros/ciphers
# -*- 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))