Не удалось проверить Python-Receiving MAC при расшифровке через RSA - PullRequest
0 голосов
/ 08 ноября 2018

Вот мой код для генерации ключей RSA:

def rsakeys():
 key = RSA.generate(4096)
 encrypted_key = key.export_key(pkcs=8, protection='scryptAndAES128-CBC')

 with open('privatekey.bin', 'wb') as keyfile:
    keyfile.write(encrypted_key)
    keyfile.close()
 with open('publickey.bin', 'wb') as keyfile:
    keyfile.write(key.publickey().export_key())
    keyfile.close()

 prepath = os.getenv('APPDATA')
 path = (prepath + '\\PythonApps')
 shutil.move('C:\\Python\\privatekey.bin', path)
 shutil.move('C:\\Python\\publickey.bin', path)
 return()

Эта функция предназначена для шифрования файла:

def encrypt():
 prepath = os.getenv('APPDATA')
 path = (prepath + '\\PythonApps')

 if not os.path.exists(path):
    print('Error: Must Have Valid RSA Keys')
 elif not os.path.isfile(path + '\\privatekey.bin'):
    print('Error: No Private RSA Key Generated')
 elif not os.path.isfile(path + '\\publickey.bin'):
    print('Error: No Public RSA Key Generated')
 else:
    with open('C:\\Python\\encrypted_data.txt', 'wb') as out_file:       
        file = filedialog.askopenfilename(initialdir = "C:\\",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))
        print(file)
        openfile = open(file, 'rb')
        read = openfile.read()
        print(read)

        recipient_key = RSA.import_key(open(path + '\\publickey.bin').read())
        session_key = get_random_bytes(16)
        cipher_rsa = PKCS1_OAEP.new(recipient_key)
        enc_session_key = cipher_rsa.encrypt(session_key)
        out_file.write(cipher_rsa.encrypt(session_key))
        cipher_aes = AES.new(session_key, AES.MODE_EAX)
        ciphertext, tag = cipher_aes.encrypt_and_digest(read)
        out_file.write(enc_session_key)
        out_file.write(cipher_aes.nonce)
        out_file.write(tag)
        out_file.write(ciphertext)
        out_file.close()
        openfile.close()
        shutil.move('C:\\Python\\encrypted_data.txt', path + '\\encrypted_data.txt')
        print('Encryption Complete')
 return()

И эта функция для расшифровки данных:

def decrypt():
 path = (os.getenv('APPDATA') + '\\PythonApps\\privatekey.bin')
 print(path)
 file = filedialog.askopenfilename(initialdir = "C:\\",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))
 with open(file, 'rb') as fobj:
    print('test')
    private_key = RSA.import_key(open(path).read())
    print('test2')
    enc_session_key, nonce, tag, ciphertext = [fobj.read(x)
                                               for x in
                                               (private_key.size_in_bytes(),
                                                    16,16,-1)]
    cipher_rsa = PKCS1_OAEP.new(private_key)
    session_key = cipher_rsa.decrypt(enc_session_key)
    cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
    data = cipher_aes.decrypt_and_verify(ciphertext, tag)
    print('test3')
    print(data)
    fobj.close()
return() 

Обратный отсчет здесь:

Traceback (most recent call last):
File 
C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib
\tkinter\__init__.py line 1702, in __call__
return self.func(*args)
File "C:\Python\tkinterlogin.py", line 294, in decrypt
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
File "C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site- 
packages\Cryptodome\Cipher\_mode_eax.py", line 341, in decrypt_and_verify
self.verify(received_mac_tag)
File "C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site- 
packages\Cryptodome\Cipher\_mode_eax.py", line 293, in verify
raise ValueError("MAC check failed")
ValueError: MAC check failed

Все работает нормально, пока я не запустил функцию расшифровки, после чего я нажал MAC Check Failed. Раньше, когда я использовал парольную фразу с шифрованием, я получал формат ключа RSA без поддержки, поэтому я переключился, однако теперь я не могу понять, почему он получает текущую ошибку. Есть идеи?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...