Example #1
0
 def __key_exchange(self):
     server_public_key_data = self.__socket.recv(BUFFER_SIZE)
     server_public_key = Cipher.unpack(server_public_key_data)
     to_send = self.__key.pack() + IN_PACK_SEPARATOR + Cipher.hash(self.__key.pack())
     to_send = server_public_key.encrypt(to_send)
     self.__socket.send(to_send)
     return True
Example #2
0
 def __key_exchange(self, sock):
     sock.send(self.__public_key.public_key().pack())
     data = sock.recv(BUFFER_SIZE)
     key = self.__public_key.decrypt(data)
     key, his_hashed_key = key.split(IN_PACK_SEPARATOR)
     if Cipher.hash(key) == his_hashed_key:
         key = Cipher.unpack(key)
         return key
def main(argv):
    plaintext = None
    password = None
    topic = "topic"
    ciphertext = None
    userTriedAction = False
    # helper : http://www.diveintopython.net/scripts_and_streams/command_line_arguments.html
    # try:
    #     opts, args = getopt.getopt(argv, "hg:d", ["help", "p=", "c=", "k="])
    # except getopt.GetoptError:
    #     usage()
    #     sys.exit(2)
    # for opt, arg in opts:
    #     if opt in ("-h", "--help"):
    #         usage()
    #         sys.exit()
    #     elif opt in ("-p", "--plaintext"):
    #         plaintext = arg
    #         userTriedAction = True
    #     elif opt in ("-c", "--ciphertext"):
    #         ciphertext = arg
    #         userTriedAction = True
    #     elif opt in ("-k", "--key"):
    #         password = arg
    #         userTriedAction = True

    # print("args: ", plaintext, key, ciphertext)
    try:
        plaintext = argv[0]
        password = argv[1]
    except:
        if len(argv) == 0:
            usage()
            print("\nNo argument provided. Entering development mode.")
            dev(argv)
        else:
            print("Invalide arguments.")
            usage()
            sys.exit(2)

    try:
        topic = argv[3]
    except:
        pass

    if plaintext != None and password != None:
        db = Database.TweetDatabase()
        cipher = Cipher()
        spam,key = cipher.encode(plaintext, password, "topic", db)

        print("Here is your spam:")
        print(spam)

        print("Checking decoding process: here is the message hidden in the spam:")
        print(cipher.decode(spam,key))
    else:
        usage()
Example #4
0
    def decrypt_music(self):
        key = self.read_key()
        x = Cipher(key)
        path = path_to_file
        with open(path, 'rb') as musicfile:
            decsound = musicfile.read()

            assert decsound is not None, 'CANNOT READ SOUND FILE!!!'
            decsound = x.decrypt(decsound)
        return decsound
def dev(argv):
    db = Database.TweetDatabase()
    cipher = Cipher()
    print()
    print()
    spam,key = cipher.encode("Your majesty the quee", "awesome password", "topic", db)
    print("Here is your spam:")
    print(spam)

    print(cipher.decode(spam,key))
Example #6
0
 def decrypt(self, password):
   c = Cipher(password)
   decrypted = c.decode(self.decoded)
   if not decrypted:
     logging.error('Did not decode properly.')
     return False
   to_write = base64.b64decode(decrypted)
   with open('decrypted.jpg', 'wb') as fh:
     fh.write(to_write)
   return True
Example #7
0
 def decrypt(self, password):
     c = Cipher(password)
     decrypted = c.decode(self.decoded)
     if not decrypted:
         logging.error('Did not decode properly.')
         return False
     to_write = base64.b64decode(decrypted)
     with open('decrypted.jpg', 'wb') as fh:
         fh.write(to_write)
     return True
Example #8
0
def main(argv):
    # helper : http://www.diveintopython.net/scripts_and_streams/command_line_arguments.html
    usage()
    db = Database.TweetDatabase()
    cipher = Cipher()
    print()
    print()
    spam = cipher.encode("your plaintext", "awesome password", "topic", db)
    print("Here is your spam:")
    print(spam)

    print(cipher.decode(spam,"awesome password"))
Example #9
0
    def main(self, *args, **kwargs):
        secret = self.read_key()
        x = Cipher(secret)
        content = None


        with open(path_to_file, 'rb') as fd:
            content = fd.read()
        assert content is not None, 'CANNOT READ FILE TO ENCRYPTION!!!'

        a = x.encrypt(content)
        with open('output1', 'wb') as fd:
            fd.write(a)
Example #10
0
    def __init__(self, window_name):
        self.backend = BackendJson("data")
        self.cipher = Cipher()

        self.root = tkinter.Tk()
        self.root.title(window_name)
        # self.root.iconbitmap("./ico/icon.ico")
        # размер и положение окна (середира экрана)
        wx = self.root.winfo_screenwidth()
        wy = self.root.winfo_screenheight()
        x = int(wx / 2 - 600 / 2)
        y = int(wy / 2 - 400 / 2)
        self.root.geometry(f"600x400+{x}+{y}")
        self.root.resizable(False, False)
        # вызов начального фрейма
        self.frame_home()
Example #11
0
 def __decrypt(self, data):
     result, hashed = data.split(IN_PACK_SEPARATOR)
     result = self.__key.decrypt(result)
     if Cipher.hash(result) == hashed:
         return result
     else:
         raise EnvironmentError("CLIENT UNAUTHORISED")
Example #12
0
 def get_cipher(self):
     """Return an M2Crypto.SSL.Cipher object for this connection; if the
     connection has not been initialised with a cipher suite, return None."""
     c = m2.ssl_get_current_cipher(self.ssl)
     if c is None:
         return None
     return Cipher(c)
Example #13
0
 def __decrypt(self, data):
     data, hashed = data.split(IN_PACK_SEPARATOR)
     data = self.__key.decrypt(data)
     if Cipher.hash(data) == hashed:
         return data
     else:
         raise EnvironmentError("Server Unauthorised")
Example #14
0
 def start(self):
     """
     Starts the server
     """
     if self.starting or self.running:
         raise NameError('Already running or starting...')
     self.starting = True
     self.__signature = Cipher.crate_signature()
     self.__public_key = Cipher()
     self.__print("Updating database...")
     pythoncom.CoInitialize()
     current_arp = NetMap.map()
     pythoncom.CoUninitialize()
     database = self.__database.read()
     # Loop for updating the state of the computer
     for computer in database:
         if computer.ip == gethostbyname(gethostname()):
             computer.active = True
             self.__database.update_state(computer)
         elif computer not in current_arp:
             computer.active = False
             self.__database.update_state(computer)
     # Loop for updating the database
     for computer in current_arp:
         if computer not in database:
             self.__database.add_row(computer)
             database = self.__database.read()
     self.__print("Database updated.")
     if not exists(DOWNLOAD_UPLOAD):
         makedirs(DOWNLOAD_UPLOAD)
     network_scan_thread = Thread(target=self.__network_scan)
     network_scan_thread.setDaemon(True)
     network_scan_thread.start()
     broadcast_announce_thread = Thread(target=self.__broadcast_announce)
     broadcast_announce_thread.setDaemon(True)
     broadcast_announce_thread.start()
     self.__main_socket.bind(("0.0.0.0", SERVER_PORT))
     self.__main_socket.listen(1)
     self.starting = False
     self.running = True
     self.__run()
Example #15
0
 def __init__(self):
     self.__socket = socket.socket()
     self.__mac = get_mac()
     self.__name = socket.gethostname()
     self.__processes = []
     self.__key = Cipher.random_key()
     self.handle_functions = {
         "CreateFile": self.__create_file,
         "DeleteFile": self.__delete_file,
         "CreateProcess": self.__create_process,
         "TerminateProcess": self.__terminate_process,
         "UpdateProcesses": self.__send_processes,
         "GetFile": self.__get_file,
         "Upload": self.__send_file
     }
Example #16
0
    def gen_cipher_file(self, cipherdata, modedata):
        headers = set([h for m in cipherdata + modedata for h in m['headers']])
        ciphers = [Cipher(defaultdict(none_factory(), c)) for c in cipherdata]
        modes = [CipherMode(defaultdict(none_factory(), m),
                            [c for c in cipherdata
                             if c.get('family') in ('aes', 'camellia')])
                 for m in modedata]
        classes = ciphers + modes
        self.objects.extend(classes)
        self.ciphers = ciphers

        self.write_class_file(self.cipher_file, classes, headers)
        self.write_doc_file(self.cipher_doc_file, "Ciphers",
                            docstrings.cipher_example, ciphers)
        self.write_doc_file(self.ciphermode_doc_file, "Cipher Modes",
                            docstrings.ciphermode_example, modes)
Example #17
0
class Server(object):
    # constructor
    def __init__(self):
        self.__address = gethostbyname(gethostname())
        self.__main_socket = socket()
        self.__database = ComputerDatabase()
        self.__database_lock = Lock()
        self.__announce_socket = socket(AF_INET, SOCK_DGRAM)
        self.running = False
        self.starting = False
        self._connected_clients = ClientList()
        self.__signature = None
        self.__public_key = None

    # starts server - updates database and starts threads
    def start(self):
        """
        Starts the server
        """
        if self.starting or self.running:
            raise NameError('Already running or starting...')
        self.starting = True
        self.__signature = Cipher.crate_signature()
        self.__public_key = Cipher()
        self.__print("Updating database...")
        pythoncom.CoInitialize()
        current_arp = NetMap.map()
        pythoncom.CoUninitialize()
        database = self.__database.read()
        # Loop for updating the state of the computer
        for computer in database:
            if computer.ip == gethostbyname(gethostname()):
                computer.active = True
                self.__database.update_state(computer)
            elif computer not in current_arp:
                computer.active = False
                self.__database.update_state(computer)
        # Loop for updating the database
        for computer in current_arp:
            if computer not in database:
                self.__database.add_row(computer)
                database = self.__database.read()
        self.__print("Database updated.")
        if not exists(DOWNLOAD_UPLOAD):
            makedirs(DOWNLOAD_UPLOAD)
        network_scan_thread = Thread(target=self.__network_scan)
        network_scan_thread.setDaemon(True)
        network_scan_thread.start()
        broadcast_announce_thread = Thread(target=self.__broadcast_announce)
        broadcast_announce_thread.setDaemon(True)
        broadcast_announce_thread.start()
        self.__main_socket.bind(("0.0.0.0", SERVER_PORT))
        self.__main_socket.listen(1)
        self.starting = False
        self.running = True
        self.__run()

    # the main running method of the server
    def __run(self):
        """
        Actual main code of the server
        """
        self.__print("Server started!")
        while True:
            to_read, to_write, error = select([self.__main_socket], [], [])
            for sock in to_read:
                if sock is self.__main_socket:
                    client_socket, client_address = self.__main_socket.accept()
                    for computer in self.__database.read():
                        if computer.ip == client_address[0]:
                            new_client_thread = Thread(target=self.__new_client, args=[client_socket, computer])
                            new_client_thread.setDaemon(True)
                            new_client_thread.start()

    # handles a newly connected client
    def __new_client(self, client_socket, computer):
        key = self.__key_exchange(client_socket)
        if isinstance(key, Cipher):
            self._connected_clients.append(ClientInterface(client_socket, computer, key))

    # Operates the key exchange with client
    def __key_exchange(self, sock):
        sock.send(self.__public_key.public_key().pack())
        data = sock.recv(BUFFER_SIZE)
        key = self.__public_key.decrypt(data)
        key, his_hashed_key = key.split(IN_PACK_SEPARATOR)
        if Cipher.hash(key) == his_hashed_key:
            key = Cipher.unpack(key)
            return key

    # Has it's own thread - announces the server address to the network
    def __broadcast_announce(self):
        """
        Runs in a thread. Announces the server's existence in the network
        """
        message = SERVER_ANNOUNCE_MESSAGE
        self.__announce_socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        while True:
            self.__announce_socket.sendto(message, ("<broadcast>", BROADCAST_PORT))
            sleep(ANNOUNCE_SLEEP_TIME)

    
    def __network_scan(self):
        """
        Scans the network
        """
        while True:
            sleep(NET_SCAN_WAIT)
            pythoncom.CoInitialize()
            current_arp = NetMap.map()
            pythoncom.CoUninitialize()
            database = self.__database.read()
            for computer in database:
                if computer.ip == gethostbyname(gethostname()):
                    computer.active = True
                    self.__database.update_state(computer)
                elif computer not in current_arp:
                    computer.active = False
                    self.__database.update_state(computer)
            for computer in current_arp:
                if computer not in database:
                    self.__database.add_row(computer)
                    database = self.__database.read()

    def __print(self, data):
        print data

    def do_action(self, computer, hour, minute, second, action):
        if isinstance(computer, Computer):
            for other_computer in self.__database.read():
                if other_computer == computer:
                    now = datetime.now()
                    my_time = datetime(now.year, now.month, now.day, int(hour), int(minute), int(second))
                    to_wait = (my_time - now).seconds
                    wait_thread = Thread(target=self.__wait_to_action, args=(to_wait, action, computer))
                    wait_thread.start()
                    return

    def do_action_now(self, computer, action):
        if isinstance(computer, Computer):
            for other_computer in self.__database.read():
                if other_computer == computer:
                    self.__wait_to_action(0, action, computer)
                    return

    def __wait_to_action(self, time_to_wait, action, computer):
        sleep(time_to_wait)
        if action == "shutdown":
            client = self.__find_client(computer)
            if isinstance(client, ClientInterface):
                self._connected_clients.remove(client)
            computer.shutdown()
        else:
            computer.wake_up()
        self.__database.update_state(computer)

    def make_computers_dictionary(self):
        dictionary = self.__database.make_dictionary()
        dictionary["CONNECTED"] = []
        for i in xrange(len(dictionary["MAC"])):
            dictionary["CONNECTED"].append(str(Computer(dictionary["MAC"][i], dictionary["IP"][i]) in self._connected_clients))
        return dictionary

    def __find_client(self, computer):
        for client in self._connected_clients:
            if computer == client:
                return client

    def computer_data(self, computer):
        client = self.__find_client(computer)
        return {"MAC": client.get_mac(),
                "IP": client.get_ip(),
                "HOST": client.name}

    def get_processes_data(self, computer):
        client = self.__find_client(computer)
        if isinstance(client, ClientInterface):
            try:
                client.update_processes()
            except:
                self._connected_clients.remove(client)
            else:
                processes_list = [dict(NAME=process.name, PID=process.pid, PARENT_ID=process.parent_id) for process in client.processes]
                return processes_list

    def terminate_process(self, computer, processes):
        client = self.__find_client(computer)
        if isinstance(client, ClientInterface):
            try:
                result = client.terminate(processes)
            except:
                self._connected_clients.remove(client)
            else:
                return result

    def open_process(self, computer, command):
        client = self.__find_client(computer)
        if isinstance(client, ClientInterface):
            try:
                result = client.open_process(command)
            except:
                self._connected_clients.remove(client)
            else:
                return result

    def get_file(self, computer, directory):
        client = self.__find_client(computer)
        if isinstance(client, ClientInterface):
            try:
                result = client.send_files(directory)
            except:
                self._connected_clients.remove(client)
            else:
                return {
                    'NAME': directory,
                    'ITEMS': result
                }

    def delete_file(self, computer, directory):
        client = self.__find_client(computer)
        if isinstance(client, ClientInterface):
            try:
                result = client.delete_file(directory)
            except:
                self._connected_clients.remove(client)
            else:
                return result

    def create_file(self, computer, path, name):
        client = self.__find_client(computer)
        if isinstance(client, ClientInterface):
            try:
                result = client.create_file(path, name)
            except:
                self._connected_clients.remove(client)
            else:
                return result

    def add_computer(self, computer):
        if isinstance(computer, Computer):
            if re.match(MAC_REGULAR_EXPRESSION, computer.mac):
                if re.match(IP_REGULAR_EXPRESSION, computer.ip):
                    if NetMap.can_ip_in_my_network(computer.ip):
                        computer.active = False
                        self.__database.add_row(computer)
                        return "Computer successfully added."
                    return "The IP address entered cannot exist in this network"
                return "Invalid IP format"
            return "Invalid MAC format"

    def download(self, computer, directory):
        client = self.__find_client(computer)
        if isinstance(client, ClientInterface):
            file_data = client.download(directory)
            file_name = directory.split('\\')[-1]
            file_dump = open(DOWNLOAD_UPLOAD + '\\' + file_name, 'wb+')
            file_dump.write(file_data)
            file_dump.close()
            return file_name

    def remote_desktop(self, computer_list):
        for computer in computer_list:
            subprocess.Popen(['mstsc', '/v:' + computer.ip])
Example #18
0
 def run(self, data, _key):
     state = State(data)
     key = Key(_key)
     cipher = Cipher(state, key)
     cipher.encrypt()
     cipher.decrypt()
Example #19
0
class Interface:
    def __init__(self, window_name):
        self.backend = BackendJson("data")
        self.cipher = Cipher()

        self.root = tkinter.Tk()
        self.root.title(window_name)
        # self.root.iconbitmap("./ico/icon.ico")
        # размер и положение окна (середира экрана)
        wx = self.root.winfo_screenwidth()
        wy = self.root.winfo_screenheight()
        x = int(wx / 2 - 600 / 2)
        y = int(wy / 2 - 400 / 2)
        self.root.geometry(f"600x400+{x}+{y}")
        self.root.resizable(False, False)
        # вызов начального фрейма
        self.frame_home()

    # создание фреймa
    def create_frames(self):
        return tkinter.Frame(self.root, width=600, height=400)

    # главный экран
    def frame_home(self):
        f_home = self.create_frames()
        f_home.place(relx=0.5, rely=0.5, anchor="center")
        self.__author(f_home)

        welcome_text = "Добро пожаловать!\nДанная программа поможет вам хранить\nи управлять Вашими паролями"
        tkinter.Label(f_home, font="Arial 15",
                      text=welcome_text).place(relx=0.5, rely=0.1, anchor="n")
        # кнопки
        buttons = ["Добавить", "Удалить", "Показать"]
        x = 80
        y = 300
        for btn in buttons:
            pressing = lambda but=btn: self.button_logics(but)
            tkinter.Button(
                f_home,
                text=btn,
                font="Arial 15",
                command=pressing,
            ).place(x=x, y=y, width=110, height=50)
            x += 160
        # ввод ключа шифрования
        tkinter.Label(
            f_home,
            font="Arial 10",
            text="Ключ шифрования",
        ).place(relx=0.05, rely=0.45, anchor="w")
        self.scrypt_key = tkinter.Entry(f_home, font="Arial 10")
        self.scrypt_key.place(relx=0.05, rely=0.5, anchor="w", width=480)
        tkinter.Button(
            f_home,
            font="Arial 7",
            text="Добавить ключ",
            command=lambda but="add_key": self.button_logics(but),
        ).place(relx=0.855, rely=0.5, anchor="w")
        self.use_scrypt_key = tkinter.Label(
            f_home, font="Arial 7", text="Используестя ключ по умолчанию")
        self.use_scrypt_key.place(relx=0.5, rely=0.53, anchor="n")

    # раздел добавления
    def frame_add(self):
        f_add = self.create_frames()
        f_add.place(relx=0.5, rely=0.5, anchor="center")
        self.button_back(f_add)
        self.__author(f_add)

        self.descriptions = {
            "Ресурс": None,
            "Ваш логин": None,
            "Ваш пароль": None
        }
        y = 10
        for description in self.descriptions.keys():
            tkinter.Label(f_add, font="Arial 15",
                          text=description).place(relx=0.5, y=y, anchor="n")
            self.descriptions[description] = tkinter.Entry(
                f_add,
                font="Arial 15",
                width=30,
            )
            self.descriptions[description].place(relx=0.5,
                                                 y=y + 30,
                                                 anchor="n")
            y += 100

        tkinter.Button(
            f_add,
            command=lambda but="add_data": self.button_logics(but),
            text="Сохранить",
            font="Arial 16",
            width=20,
        ).place(relx=0.5, rely=0.8, anchor="n")

    # раздел удаления
    def frame_del(self):
        f_del = self.create_frames()
        f_del.place(relx=0.5, rely=0.5, anchor="center")
        self.button_back(f_del)
        self.__author(f_del)

        self.temp_f_frame = f_del

        self.del_list = tkinter.Listbox(f_del,
                                        font="Arial 10",
                                        selectmode=tkinter.MULTIPLE,
                                        bd=1)
        tkinter.Button(f_del,
                       command=lambda but="del_data": self.button_logics(but),
                       font="Arial 15",
                       text="Удалить").place(relx=0.5, rely=0.85, anchor="n")

        # работа со списком
        self.data = self.backend.read_file()
        for atr in self.data:
            self.del_list.insert(tkinter.END, f"{self.cipher.decipher(atr)}")

        self.del_list.place(relx=0.5, y=3, anchor="n", width=444, height=330)

    # раздел просмотра
    def frame_view(self):
        f_view = self.create_frames()
        f_view.place(relx=0.5, rely=0.5, anchor="center")
        self.button_back(f_view)
        self.__author(f_view)

        self.info = tkinter.Text(f_view, font="Arial 10")

        # работа со списком
        data = self.backend.read_file()
        for k, v in data.items():
            out = f"{4*' '}{self.cipher.decipher(k)}\n" \
                  f"\tLogin: {self.cipher.decipher(v['login'])}\n" \
                  f"\tPassword: {self.cipher.decipher(v['password'])}\n" \
                  f"{110*'-'}"
            self.info.insert(tkinter.END, out)

        self.info.place(relx=0.5, y=3, anchor="n", width=446, height=380)

    # логика нажатий на кнопки
    def button_logics(self, pressing):
        if pressing == "Добавить":
            self.frame_add()
        elif pressing == "Удалить":
            self.frame_del()
        elif pressing == "Показать":
            self.frame_view()
        elif pressing == "add_data":
            self.add()
        elif pressing == "del_data":
            self.dell()
        elif pressing == "add_key":
            self.add_scrypt_key()

    # Кнопка добавить
    def add(self):
        resource = self.cipher.encipher(self.descriptions["Ресурс"].get())
        login = self.cipher.encipher(self.descriptions["Ваш логин"].get())
        password = self.cipher.encipher(self.descriptions["Ваш пароль"].get())
        if resource and login and password:
            # очистить поля
            self.descriptions["Ресурс"].delete(0, tkinter.END)
            self.descriptions["Ваш логин"].delete(0, tkinter.END)
            self.descriptions["Ваш пароль"].delete(0, tkinter.END)
            # добавление данных в память
            self.backend.add_to_file(resource, login, password)

    # кнопка удалить
    def dell(self):
        if self.data:
            need_del = [
                self.cipher.encipher(i)
                for i in self.del_list.selection_get().split("\n")
            ]
            self.backend.del_from_file(need_del)
            # перезапуск фрейма
            self.temp_f_frame.destroy()
            self.frame_del()

    # кнопка добавить клюс шифрования
    def add_scrypt_key(self):
        key = self.scrypt_key.get()
        if key:
            self.cipher.scrypt_key_set(key.lower())
            self.use_scrypt_key["text"] = f"Используется ключ: {key}"
        else:
            self.cipher.scrypt_key_default()
            self.use_scrypt_key["text"] = "Используестя ключ по умолчанию"

    # кнопка "назад"
    def button_back(self, frame):
        tkinter.Button(
            frame,
            text="< Назад",
            font="Arial 8",
            command=lambda: frame.destroy(),
        ).place(x=3, y=3, anchor="nw")

    # запуск окна
    def start(self):
        self.root.mainloop()

    # автор "водяной знак"
    def __author(self, root):
        my_name = "Programm by Rybak A."
        tkinter.Label(root, font="Tahoma 7", text=my_name,
                      fg="Blue").place(relx=1, rely=1, anchor="se")
Example #20
0
  def encrypt(self, password):
    # Base64 of the encrypted image data.
    c = Cipher(password)
    self.b64encrypted = c.encode(base64.b64encode(self.bin_image))
    logging.debug('Encrypted b64: ' + self.b64encrypted)
    logging.info('Length of b64encoded: %d.' % len(self.b64encrypted))
    to_hexify = self.b64encrypted

    # ECC encode to hex_string.
    if FLAGS.ecc:
      logging.info('ECCoder encoding input length:  %d.' % \
                     len(self.b64encrypted))
      coder = ECCoder(FLAGS.ecc_n, FLAGS.ecc_k, FLAGS.threads)
      encoded = coder.encode(self.b64encrypted)
      logging.info('ECCoder encoding output length: %d.' % len(encoded))
      to_hexify = encoded

    # Hexified data for encoding in the uploaded image.
    hex_data = binascii.hexlify(to_hexify)
    self.enc_orig_hex_data = hex_data
    num_data = len(hex_data)
    logging.debug('Original encrypted hex Data: ' + hex_data)

    if FLAGS.extra_logs:
      with open('hex_data.log', 'w') as _:
        for i in range(0, len(hex_data), 80):
          _.write(hex_data[i:min(i+80, len(hex_data))] + '\n')

    logging.info('Length of hex_data: %d' % num_data)
    width, length = self.image.size
    width_power_2 = int(math.ceil(math.log(width, 2)))
    TARGET_WIDTH = 2 ** (width_power_2 + 1)
    logging.info('Width: %d.' % TARGET_WIDTH)

    width = int(TARGET_WIDTH / (self.block_size * 2.))
    height = int(math.ceil(num_data / (1. * width)))
    logging.info('Encrypted image (w x h): (%d x %d).' % (width, height))
    logging.info('Expected image (w x h): (%d x %d).' % \
                    (TARGET_WIDTH, height*self.block_size))

    # Create the base for the encrypted image.
    rgb_image_width = width * self.block_size * 2
    rgb_image_height = height * self.block_size

    self.rgb_image = Image.new('RGB', (rgb_image_width, rgb_image_height))
    colors = [(255,255,255), (255,0,0), (0,255,0), (0,0,255)]

    draw = ImageDraw.Draw(self.rgb_image)
    for i, hex_datum in enumerate(hex_data):
      #logging.info('hex_datum (%d): %s.' % (i, hex_datum))
      hex_val = int(hex_datum, 16)
      base4_1 = int(hex_val / 4.0) # Implicit floor.
      base4_0 = int(hex_val - (base4_1 * 4))
      y_coord = int(i / (1. * width))
      x_coord = int(i - (y_coord * width))

      # base4_0
      base4_0_x = int(x_coord * self.block_size * 2)
      base4_0_y = int(y_coord * self.block_size)
      base4_0_rectangle = \
          [(base4_0_x, base4_0_y),
           (base4_0_x + self.block_size, base4_0_y + self.block_size)]
      draw.rectangle(base4_0_rectangle, fill=colors[base4_0])

      # base4_1
      base4_1_x = int((x_coord * self.block_size * 2) + self.block_size)
      base4_1_y = int(y_coord * self.block_size)
      base4_1_rectangle = \
        [(base4_1_x, base4_1_y),
         (base4_1_x + self.block_size, base4_1_y + self.block_size)]
      draw.rectangle(base4_1_rectangle, fill=colors[base4_1])

    filename = 'rgb.jpg'
    logging.info('Saving %s (quality: %d).' % \
                   (filename, FLAGS.encrypted_image_quality))
    self.rgb_image.save(filename, quality=FLAGS.encrypted_image_quality)
    return filename
Example #21
0
 def __encrypt(self, data):
     result = self.__key.encrypt(data) + IN_PACK_SEPARATOR + Cipher.hash(data)
     return result
Example #22
0
    def encrypt(self, password):
        # Base64 of the encrypted image data.
        c = Cipher(password)
        self.b64encrypted = c.encode(base64.b64encode(self.bin_image))
        logging.debug('Encrypted b64: ' + self.b64encrypted)
        logging.info('Length of b64encoded: %d.' % len(self.b64encrypted))
        to_hexify = self.b64encrypted

        # ECC encode to hex_string.
        if FLAGS.ecc:
            logging.info('ECCoder encoding input length:  %d.' % \
                           len(self.b64encrypted))
            coder = ECCoder(FLAGS.ecc_n, FLAGS.ecc_k, FLAGS.threads)
            encoded = coder.encode(self.b64encrypted)
            logging.info('ECCoder encoding output length: %d.' % len(encoded))
            to_hexify = encoded

        # Hexified data for encoding in the uploaded image.
        hex_data = binascii.hexlify(to_hexify)
        self.enc_orig_hex_data = hex_data
        num_data = len(hex_data)
        logging.debug('Original encrypted hex Data: ' + hex_data)

        if FLAGS.extra_logs:
            with open('hex_data.log', 'w') as _:
                for i in range(0, len(hex_data), 80):
                    _.write(hex_data[i:min(i + 80, len(hex_data))] + '\n')

        logging.info('Length of hex_data: %d' % num_data)
        width, length = self.image.size
        width_power_2 = int(math.ceil(math.log(width, 2)))
        TARGET_WIDTH = 2**(width_power_2 + 1)
        logging.info('Width: %d.' % TARGET_WIDTH)

        width = int(TARGET_WIDTH / (self.block_size * 2.))
        height = int(math.ceil(num_data / (1. * width)))
        logging.info('Encrypted image (w x h): (%d x %d).' % (width, height))
        logging.info('Expected image (w x h): (%d x %d).' % \
                        (TARGET_WIDTH, height*self.block_size))

        # Create the base for the encrypted image.
        rgb_image_width = width * self.block_size * 2
        rgb_image_height = height * self.block_size

        self.rgb_image = Image.new('RGB', (rgb_image_width, rgb_image_height))
        colors = [(255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255)]

        draw = ImageDraw.Draw(self.rgb_image)
        for i, hex_datum in enumerate(hex_data):
            #logging.info('hex_datum (%d): %s.' % (i, hex_datum))
            hex_val = int(hex_datum, 16)
            base4_1 = int(hex_val / 4.0)  # Implicit floor.
            base4_0 = int(hex_val - (base4_1 * 4))
            y_coord = int(i / (1. * width))
            x_coord = int(i - (y_coord * width))

            # base4_0
            base4_0_x = int(x_coord * self.block_size * 2)
            base4_0_y = int(y_coord * self.block_size)
            base4_0_rectangle = \
                [(base4_0_x, base4_0_y),
                 (base4_0_x + self.block_size, base4_0_y + self.block_size)]
            draw.rectangle(base4_0_rectangle, fill=colors[base4_0])

            # base4_1
            base4_1_x = int((x_coord * self.block_size * 2) + self.block_size)
            base4_1_y = int(y_coord * self.block_size)
            base4_1_rectangle = \
              [(base4_1_x, base4_1_y),
               (base4_1_x + self.block_size, base4_1_y + self.block_size)]
            draw.rectangle(base4_1_rectangle, fill=colors[base4_1])

        filename = 'rgb.jpg'
        logging.info('Saving %s (quality: %d).' % \
                       (filename, FLAGS.encrypted_image_quality))
        self.rgb_image.save(filename, quality=FLAGS.encrypted_image_quality)
        return filename
Example #23
0
from Cipher import Cipher

cip = Cipher()

key = input('Введи ключ: ')
text = input('Введи слово для шифрования: ')
key_text = input('Введи слово для расшифрования: ')

d = cip.cipher(key, text, key_text)

print(d)




Example #24
0
 def __init__(self, s, size_element=1, keep_spaces=False, key=None):
     Cipher.__init__(self, s, size_element, keep_spaces)
     self.key = key
Example #25
0
def do_encryption(message, offset):
    alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
    process_method = CaesarCharProc(alphabet, offset)
    cipher = Cipher(process_method)
    encrypted_message = cipher.encrypt(message)
    print(f'Encrypted: {encrypted_message}')