@users12332

Что за кусок кода на Python?

Изучаю Python.
Подскажите что за кусок кода?

from Crypto.Cipher import crypto
import os
import codecs
import binascii
import hashlib

# Инициализация
PADDING = "{"

# Инициализация для генерации ключа
KEY = None


def _padding(message):
    """Проверка длины"""

    remainder = len(message) % 16
    if remainder == 0:
        return message
    else:
        return ''.join([message, PADDING * (16 - remainder)])


def _split_message(message, block_size):
    

    # Исключение

    num_of_blocks = int(len(message) / block_size)

    message_in_blocks = [message[i * block_size:(i + 1) * block_size] for i in range(num_of_blocks)]

    return message_in_blocks


def encrypt(key, message):
    
    

    # Преобразование
    message = _padding(message)
    message_blocks = _split_message(message, 16)

    IV = os.urandom(16)

    encrypter = crypto.new(key, AES.MODE_CBC, IV)
    ciphertext_blocks = [encrypter.encrypt(message_block) for message_block in message_blocks]

    ciphertext_blocks_in_hex = [(codecs.encode(IV, 'hex_codec')).decode("utf-8")] + \
                               [(codecs.encode(ciphertext_block, 'hex_codec')).decode("utf-8")
                                for ciphertext_block in ciphertext_blocks]
    ciphertext = ''.join(ciphertext_blocks_in_hex)

    return ciphertext


def decrypt(key, ciphertext):
    
    ciphertext_blocks_in_hex = _split_message(ciphertext, 32)

    ciphertext_blocks = [binascii.unhexlify(ciphertext_block) for ciphertext_block in ciphertext_blocks_in_hex]

    IV = ciphertext_blocks[0]

    decrypter = crypto.new(key, AES.MODE_CBC, IV)
    ciphertext_blocks = ciphertext_blocks[1:]

    message_blocks = [(decrypter.decrypt(ciphertext_block)).decode("utf-8") for ciphertext_block in ciphertext_blocks]
    message = ''.join(message_blocks)

___________________________________________________________________________________________

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from UI import CryptoMainWindow_ui, CryptoPasswordDialog_ui
import crypto
import sys

class CryptoMainWindow(QMainWindow, CryptoMainWindow_ui.Ui_main_window):
    """Определяем атрибуты и методы"""

    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)

        # Обработчики событий
        self.button_encrypt.clicked.connect(self.encrypt_text)
        self.button_decrypt.clicked.connect(self.decrypt_text)
        self.line_edit_main_window.returnPressed.connect(self.encrypt_text)
        self.line_edit_main_window.textEdited.connect(self.edit_characters_left_label)
        self.action_clear_chat.triggered.connect(self.clear_chat)
        self.action_generate_AES_key.triggered.connect(self.generate_new_key)

        self.setFocus()

    def encrypt_text(self):
        """Обработчик метода шифрования в пуше"""

        message = self.line_edit_main_window.text()

        # Проверка
        if message and not message.isspace():
            ciphertext = crypto_.encrypt(crypto_.KEY, message)
            self.text_edit.append("<b>Encrypted:</b> {0}".format(ciphertext))
            self.line_edit_main_window.clear()
            self.edit_characters_left_label()

    def decrypt_text(self):
        """Проверяем ключ пользователя"""

        # Если длина ключа не соответствует
        ciphertext = self.line_edit_main_window.text()

        # Проверка передачи ключа пользователя
        if ciphertext and not ciphertext.isspace():
            message = crypto_.decrypt(crypto_.KEY, ciphertext)
            self.text_edit.append("<b>Decrypted:</b> {0}".format(message))
            self.line_edit_main_window.clear()
            self.edit_characters_left_label()

    def edit_characters_left_label(self):
        

        # Максимальное кол-во символов
        max_num_of_characters = 320
        num_of_characters_left = max_num_of_characters - len(self.line_edit_main_window.text())
        self.label_characters_left.setText("{0} characters left".format(num_of_characters_left))

    def clear_chat(self):
        """Чистим сообщение"""
        self.text_edit.setText("")

    def generate_new_key(self):
        """Генерация нового ключа"""


Спасибо!
  • Вопрос задан
  • 717 просмотров
Решения вопроса 1
sim3x
@sim3x
https://pypi.python.org/pypi/pycrypto
https://github.com/dlitz/pycrypto

Create a new AES cipher
https://github.com/dlitz/pycrypto/blob/master/lib/...

В указанном тобой коде шифруется массив сообщений
encrypter = crypto.new(key, AES.MODE_CBC, IV)
ciphertext_blocks = [encrypter.encrypt(message_block) for message_block in message_blocks]

спомощью AES
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы