Пример #1
0
def test_viginere_encrypt():
    plaintext = ciphertexts['plaintext']
    desired_ciphertext = ciphertexts['Viginere']

    cipher = Vigenere('classicalcipher')
    encrypted_text = cipher.encrypt(plaintext)
    print(encrypted_text)

    assert encrypted_text == desired_ciphertext
Пример #2
0
# -*- coding: utf-8 -*-
from vigenere import Vigenere
import sys

versao = sys.version_info[0]

if versao == 2:
    leitura = raw_input
elif versao == 3:
    leitura = input

txt_in = leitura(
    'Texto a ser cifrado: zfumkwkhgmeftxmgonhgmgtbibzfpmmyjhbshgbyfhxwmauduiozcgoznedifmbiefvw '
)
password = leitura('Senha:  ')

cifra = Vigenere()
txt_cifrado = cifra.encrypt(txt_in, password)
print
print('Texto cifrado: {0}'.format(txt_cifrado))
print('  Texto plano: {0}'.format(cifra.decrypt(txt_cifrado, password)))
Пример #3
0
import sys
import FileReader as fr
from vigenere import Vigenere

# extractor = FrameExtractor(
#     "awoo.mp4", "temp")
# extractor.load()
# extractor.extract()

raw_data = fr.ByteArrayToIntArray(fr.ReadFileAsByteArray("test_file.txt"))
vig = Vigenere()
vig.input_key("awoo")
vig.set_auto(False)
vig.set_full(False)
vig.set_extended(True)
encrypted = vig.encrypt(''.join([chr(i) for i in raw_data]))
encrypted = bytes(encrypted)
print("BYTE ARRAY : ", encrypted)

vig2 = Vigenere()
vig2.input_key("awoo")
vig2.set_auto(False)
vig2.set_full(False)
vig2.set_extended(True)
decrypted = vig.decrypt(''.join([chr(i) for i in encrypted]))
print(bytes(decrypted))
# vid = VideoLSB("awoo.mp4", raw_data,
#                "hidden-awoo.avi", [0, 0])
# vid.stego_data("test_file", "txt", [0, 1])
# vid.makeVideo("hidden.avi")
Пример #4
0
class Enigma:
    """
    A modified Enigma machine incorporating different cryptography algorithms.
    """
    def __init__(self, plugboard={" ": " "}, rotors=None, rotor_settings=None):
        self.base_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

        if type(plugboard) is not dict:
            self.plugboard = {" ": " "}
        else:
            self.plugboard = plugboard

        self.reflector = 'EJMZALYXVBWFCRQUONTSPIKHGD'

        if rotors is None or type(rotors) is not list:
            self.rotors = [
                list(rotor) for rotor in Rotors.CommericialEnigmaRotors
            ]
        else:
            self.rotors = rotors

        if rotor_settings is None or type(rotor_settings) is not list:
            self.rotor_settings = [0 for i in range(3)]
            self.vigenere = ['A', 'A', 'A', 'A', 'A', 'A']
            self.matrix_crypt = np.array([[1, 2, 0], [-1, 1, 3], [1, -1, -4]])
        else:
            self.rotor_settings = rotor_settings[9:12]
            self.vigenere = rotor_settings[3:6] + rotor_settings[15:18]
            self.matrix_crypt = [
                [self.base_alphabet.index(i) for i in rotor_settings[0:3]],
                [self.base_alphabet.index(i) for i in rotor_settings[6:9]],
                [self.base_alphabet.index(i) for i in rotor_settings[12:15]]
            ]

            if bool(self.rotor_settings) and all(
                    isinstance(elem, str) for elem in self.rotor_settings):
                temp = []

                for index in range(len(self.rotor_settings)):
                    temp.append(self.rotors[index].index(
                        self.rotor_settings[index]))

                self.rotor_settings = temp
            else:
                raise ValueError("Rotor settings should be letters.")

        if len(self.rotors) != len(self.rotor_settings[0:3]):
            raise ValueError(
                "Number of rotor settings should be equal to the number of rotors."
            )

        self.rotor_pointers = self.rotor_settings
        self.vig = Vigenere(
            [self.base_alphabet.index(i) for i in self.vigenere])

    @property
    def settings(self):
        """
        Returns the settings of the rotors.
        """
        ret = []

        for index in range(len(self.rotor_settings)):
            ret.append(self.rotors[index][self.rotor_settings[index]])

        return ret

    @property
    def rotor_pointer_settings(self):
        ret = []

        for index in range(len(self.rotor_settings)):
            ret.append(self.rotors[index][self.rotor_pointers[index]])

        return ret

    def set_plugboard_wiring(self, wirings):
        """
        Returns the plugboard wirings.
        """
        if type(wirings) is not dict:
            self.plugboard = {" ": " "}
        else:
            self.plugboard = wirings

    def set_rotor_settings(self, new_settings):
        """
        Sets the settings for all algorithms.
        """
        if new_settings is None or type(new_settings) is not list:
            self.rotor_settings = [0 for i in range(len(self.rotors))]
        else:
            self.rotor_settings = new_settings[9:12]

            try:
                if bool(self.rotor_settings) and all(
                        isinstance(elem, str) for elem in self.rotor_settings):
                    temp = []

                    for index in range(len(self.rotor_settings)):
                        temp.append(self.rotors[index].index(
                            self.rotor_settings[index]))

                    self.rotor_settings = temp
                else:
                    raise ValueError("Rotor settings should be letters.")
            except ValueError:
                print("Wrong key format, try again.")
                return

        self.rotor_pointers = self.rotor_settings
        self.vigenere = new_settings[3:6] + new_settings[15:18]
        self.matrix_crypt = [
            [self.base_alphabet.index(i) for i in new_settings[0:3]],
            [self.base_alphabet.index(i) for i in new_settings[6:9]],
            [self.base_alphabet.index(i) for i in new_settings[12:15]]
        ]

    def inbound_rotor_map(self, rotor_setting):
        """
        Shifts the inbound rotors based on the settings of the rotors.
        """
        shift = list(self.base_alphabet)

        for _ in range(rotor_setting):
            shift.insert(0, shift[-1])
            shift.pop(-1)

        return shift

    def outbound_rotor_map(self, rotor_setting):
        """
        Shifts the outbound rotors back to place based on the settings of the rotors.
        """
        shift = list(self.base_alphabet)

        for _ in range(rotor_setting):
            shift.append(shift[0])
            shift.pop(0)

        return shift

    def inbound_rotor(self, letter):
        """
        Inbound input rotor function from right to left.

        Note: di pa dynamic. 
        Base case: 3 rotors
        """
        # First Rotor Logic
        temp = self.inbound_rotor_map(
            self.rotor_pointers[0])[self.base_alphabet.index(letter)]

        # Second Rotor Logic
        temp = self.inbound_rotor_map(
            self.rotor_pointers[1])[self.base_alphabet.index(temp)]

        #Third Rotor Logic
        temp = self.inbound_rotor_map(
            self.rotor_pointers[2])[self.base_alphabet.index(temp)]

        return temp

    def outbound_rotor(self, letter):
        """
        Outbound input rotor function from left to right.
        """
        # Third Rotor
        temp = self.outbound_rotor_map(
            self.rotor_pointers[2])[self.base_alphabet.index(letter)]

        # Second Rotor
        temp = self.outbound_rotor_map(
            self.rotor_pointers[1])[self.base_alphabet.index(temp)]

        # First Rotor
        temp = self.outbound_rotor_map(
            self.rotor_pointers[0])[self.base_alphabet.index(temp)]

        return temp

    def turn_rotors(self):
        """
        Turns the rotors every input.
        """
        #Turn rotor 1
        self.rotor_pointers[0] += 1

        # Turn rotor 2 if rotor 1 got a full revolution
        if self.rotor_pointers[0] % 26 == 0:
            self.rotor_pointers[1] += 1
            self.rotor_pointers[0] = 0

        # Turn rotor 3 if rotor 2 got full revolution and rotor 1 does not revolve fully
        if self.rotor_pointers[1] % 26 == 0 and self.rotor_pointers[
                0] % 26 != 0 and self.rotor_pointers[1] >= 25:
            self.rotor_pointers[2] += 1
            self.rotor_pointers[1] = 1

    def plugboard_operation(self, letter):
        """
        Plugboard that swaps two letters.
        """
        if letter in self.plugboard:
            return self.plugboard[letter]
        else:
            return letter

    def reflector_operation(self, letter):
        """
        Reflects the letters to its own mapping.
        """
        return self.reflector[self.base_alphabet.index(letter)]

    def encrypt_text(self, text: str):
        """
        Encrypts a plaintext.
        """
        text = text.upper().replace(" ", "")

        encrypted_text = ""

        for letter in text:
            temp = self.plugboard_operation(letter)

            temp = self.inbound_rotor(letter)

            temp = self.reflector_operation(temp)

            temp = self.outbound_rotor(temp)

            self.turn_rotors()

            temp = self.plugboard_operation(temp)

            encrypted_text += temp

        encrypted_text = self.vig.encrypt(encrypted_text)

        processed = Crypto.convert(encrypted_text)

        encrypted_text = Crypto.encode(processed, Matrix(self.matrix_crypt))

        to_text = ""

        for code_group in encrypted_text:
            for code in code_group:
                to_text += f"{code} "

        return to_text

    def decrypt_text(self, text):
        """
        Decrypts a plaintext.
        """
        text = [int(x) for x in text.split(' ')]

        processed = [text[i:i + 3] for i in range(0, len(text), 3)]

        if len(processed[len(processed) - 1]) == 2:
            processed[len(processed) - 1].append(0)
        elif len(processed[len(processed) - 1]) == 1:
            processed[len(processed) - 1].append(0)
            processed[len(processed) - 1].append(0)

        decoder = Matrix(self.matrix_crypt)

        decoded = Crypto.decode(processed, decoder)

        decoded_message = ""

        for code_group in decoded:
            for code in code_group:
                decoded_message += f"{int(code)} "

        decoded_message = decoded_message[0:len(decoded_message) - 1]

        message = [int(x) for x in decoded_message.split(' ')]

        converted = ""

        for number in message:
            for key, value in match.items():
                if value == number:
                    converted += key

        text = converted.upper().replace(" ", "")

        text = self.vig.decrypt(text)

        decrypted_text = ""

        for letter in text:
            temp = self.plugboard_operation(letter)

            temp = self.inbound_rotor(letter)

            temp = self.reflector_operation(temp)

            temp = self.outbound_rotor(temp)

            self.turn_rotors()

            temp = self.plugboard_operation(temp)

            decrypted_text += temp

        return decrypted_text
Пример #5
0
def main():
    symbols = string.ascii_lowercase

    # first argument is the cipher
    cipher = sys.argv[1]

    # second arugment is the key
    key = sys.argv[2]

    # 3rd argument is the encrypt/Decrypt
    mode = sys.argv[3]

    # 4th argument is the input text
    input_txt = sys.argv[4]

    # 5th arugment is the output text
    output_txt = sys.argv[5]

    plainText = ''
    cipherText = ''

    text = open(input_txt)
    if mode == 'encrypt':
        plainText = text.read()
    if mode == 'decrypt':
        cipherText = text.read()

    if cipher == 'caesar' or cipher == 'Caesar':
        caesar = Caesar(key, symbols)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(caesar.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(caesar.decrypt(cipherText))
            plainText.close()

    if cipher == 'playfair' or cipher == 'Playfair':
        playfair = Playfair(key)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(playfair.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(playfair.decrypt(cipherText))
            plainText.close()

    if cipher == 'vigenere' or cipher == 'Vigenere':
        vigenere = Vigenere(key, symbols)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(vigenere.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(vigenere.decrypt(cipherText))
            plainText.close()

    if cipher == 'transposition' or cipher == 'Transposition':
        transposition = Transposition(key)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(transposition.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(transposition.decrypt(cipherText))
            plainText.close()

    if cipher == 'railfence' or cipher == 'Railfence':
        rail = RailFence(key)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(rail.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(rail.decrypt(cipherText))
            plainText.close()
Пример #6
0
from rsa import Rsa
from vigenere import Vigenere

import time
import binascii

while True:
    msg = input('Mensagem a ser cifrada: ')
    key = input('Chave: ')

    cipher = Vigenere()
    rsa = Rsa()
    start = time.time()
    cipherText = cipher.encrypt(msg.upper(), key)
    keyPublic = rsa.createPublicKey()
    keyPrivate = rsa.createPrivateKey()
    encryptedText = rsa.encript(cipherText.encode(), keyPublic)
    decodedText = rsa.decript(encryptedText, keyPrivate.upper())
    originalText = cipher.decrypt(decodedText.decode(), key)

    finish = time.time()
    print('Texto encriptado em Vigenere:', cipherText)
    print('\nTexto encriptado em RSA:', binascii.hexlify(encryptedText))
    print('\nTexto decriptado em RSA:' + decodedText.decode())
    print('\nTexto decriptado em Vigenere: ' + originalText)
    print('\nTempo de Duração: ' + str(finish - start))
    outra = input('\nQuer testar outra frase?\n1-Para sim')
    if outra != '1':
        break
Пример #7
0
def main():
    """
    DO NOT change this file
    """
    INPUT_FILE = "FDREconomics.txt"
    DECRYPT_FILE = "FDREconomicsDecrypt.txt"
    ENCRYPT_FILE = "FDREconomicsEncrypt.txt"
    DECRYPT_COMPRESS_FILE = "FDREconomicsDecryptComp.txt"

    VIGENERE_KEY = "Give PEACE a chance!!"

    print("(1) Read in original file from " + INPUT_FILE)
    print("    Print the original file:")
    print()

    file_str = open(INPUT_FILE, 'r').read()
    print(file_str)
    print()

    print("(2) Encrypt original file using key: " + VIGENERE_KEY)
    print()

    vig = Vigenere(VIGENERE_KEY)
    en_file_str = vig.encrypt(file_str)

    print("(3) Write out the encrypted file to " + ENCRYPT_FILE)
    print()

    codecs.open(ENCRYPT_FILE, 'w', encoding='utf8').write(en_file_str)

    print("(4) Read in encrypted original file from " + ENCRYPT_FILE)
    print("    Decrypt encrypted file using key")
    print("    Print out decrypted file:")
    print()

    en_file_str = codecs.open(ENCRYPT_FILE, 'r', encoding='utf8').read()
    message = vig.decrypt(en_file_str)
    print(message)
    print()

    print("(5) Write out the decrypted file to " + DECRYPT_FILE)
    print()

    open(DECRYPT_FILE, 'w').write(message)

    print("(6) Compress the original file and save in string")
    print()

    huff = Huffman()
    binary_str = huff.compress(file_str)

    print("(7) Decompress compressed file from the string")
    print("    Print out decompressed file")
    print()

    message = huff.decompress(binary_str)
    print(message)
    print()

    print("(8) Encrypt original file using key")
    print()

    vig = Vigenere(VIGENERE_KEY)
    en_file_str = vig.encrypt(file_str)

    print("(9) Compress the encrypted file and save in string")
    print()

    huff = Huffman()
    binary_str = huff.compress(en_file_str)

    print("(10) Decompress compressed encrypted file from the string")
    print()

    message = huff.decompress(binary_str)

    print("(11) Decrypt decompressed encrypted file using key")
    print("     Print out decrypted decompressed encrypted file")
    print()

    file_str = vig.decrypt(message)
    print(file_str)
    print()

    print("(12) Write out the decrypted decompressed file to " +
          DECRYPT_COMPRESS_FILE)

    open(DECRYPT_COMPRESS_FILE, 'w').write(file_str)
Пример #8
0
    if args['SHOULD_ENCRYPT']:
        key = args['ENCRYPTION_KEY']
        encrypted = substitution.encrypt(text, key)
        print(encrypted)

    elif args['SHOULD_DECRYPT']:
        decrypted = substitution.decrypt(text)
        print(decrypted)

elif args['CIPHER'] == 'VIGENERE':
    vigenere = Vigenere()

    if args['SHOULD_ENCRYPT']:
        key = args['ENCRYPTION_KEY']
        encrypted = vigenere.encrypt(text, key)
        print(encrypted)

    elif args['SHOULD_DECRYPT']:
        key_length = args['VIGENERE_KEY_LENGTH']
        decrypted = vigenere.decrypt(text, key_length)
        print(decrypted)

elif args['CIPHER'] == 'CAESAR':
    caesar = Caesar()

    if args['SHOULD_ENCRYPT']:
        key = args['ENCRYPTION_KEY']
        encrypted = caesar.encrypt(text, key)
        print(encrypted)
Пример #9
0
def main():
    """
    """
    INPUT_FILE = "FDREconomics.txt"
    DECRYPT_FILE = "FDREconomicsDecrypt.txt"
    ENCRYPT_FILE = "FDREconomicsEncrypt.txt"
    COMPRESS_DAT_FILE = "FDREconomicsComp.dat"
    ENCRYPT_COMPRESS_DAT_FILE = "FDREconomicsEncryptComp.dat"
    DECRYPT_COMPRESS_FILE = "FDREconomicsDecryptComp.txt"

    VIGENERE_KEY = "I love the USA!!"

    print("(1) Read in original file: Using " + INPUT_FILE)
    print("    Print the original file:")
    print()

    file_str = open(INPUT_FILE, 'r').read()
    print(file_str)
    print()

    print("(2) Encrypt original file using key: '{}'".format(VIGENERE_KEY))
    print()

    vig = Vigenere(VIGENERE_KEY)
    en_file_str = vig.encrypt(file_str)

    print("(3) Write out the encrypted file without compression")
    print("    Encrypted original file: Using " + ENCRYPT_FILE)
    print()

    open(ENCRYPT_FILE, 'w').write(en_file_str)

    print("(4) Read in encrypted original file: " + ENCRYPT_FILE)
    print("    Decrypt encrypted file using key")
    print("    Print out decrypted file:")
    print()

    en_file_str = open(ENCRYPT_FILE, 'r').read()
    message = vig.decrypt(en_file_str)
    print(message)
    print()

    print("(5) Write out the decrypted file")
    print("    Decrypted file: Using " + DECRYPT_FILE)
    print()

    open(DECRYPT_FILE, 'w').write(message)

    print("(6) Compress the original file without encryption")
    print("    Write out the file compressed without encryption")
    print("    Compressed original file: Using " + COMPRESS_DAT_FILE)
    print()

    huff = Huffman()
    binary_str = huff.compress(file_str)

    if BITARRAY_EXISTS:
        write_bin_file(COMPRESS_DAT_FILE, binary_str)

    print("(7) Read in compressed original file without encryption")
    print("    Decompress compressed file")
    print("    Print out decompressed file")
    print()

    if BITARRAY_EXISTS:
        binary_str = read_bin_file(COMPRESS_DAT_FILE)

    message = huff.decompress(binary_str)
    print(message)
    print()

    print("(8) Encrypt original file using key")
    print()

    vig = Vigenere(VIGENERE_KEY)
    en_file_str = vig.encrypt(file_str)

    print("(9) Compress the encrypted file")
    print("    Write out the compressed encrypted file")
    print("    Compressed encrypted file: Using " + ENCRYPT_COMPRESS_DAT_FILE)
    print()

    huff = Huffman()
    binary_str = huff.compress(en_file_str)

    if BITARRAY_EXISTS:
        write_bin_file(ENCRYPT_COMPRESS_DAT_FILE, binary_str)

    print("(10) Decompress compressed encrypted file")
    print("     Read in compressed encrypted file")
    print("     Compressed encrypted file: Using " + ENCRYPT_COMPRESS_DAT_FILE)
    print()

    if BITARRAY_EXISTS:
        binary_str = read_bin_file(ENCRYPT_COMPRESS_DAT_FILE)

    message = huff.decompress(binary_str)

    print()
    print("(11) Decrypt decompressed file using key")
    print("     Print out decrypted decompressed file")
    print()

    file_str = vig.decrypt(message)
    print(file_str)
    print()

    print("(12) Write out the decrypted decompressed file")
    print("     Decrypted decompressed file: Using " + DECRYPT_COMPRESS_FILE)

    open(DECRYPT_COMPRESS_FILE, 'w').write(file_str)