首页 > 解决方案 > 无法导入 Pycryptodome 的密钥

问题描述

最近,我开始用 Python 做加密和解密。我找到了一个名为 PyCryptodome 的包,我使用了 Crypto.PublicKey.RSA 模块。但是,我似乎无法在我的脚本中导入密钥,但它似乎在 shell 中工作正常。这是我的代码:

from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
from tkinter import Tk, messagebox, simpledialog

root = Tk()
root.withdraw()

priv_key_file = simpledialog.askstring('Decryption', 'Enter your private key file')
file_of_thing_to_decrypt = simpledialog.askstring('Decryption', 'Enter the file that is encrypted')
print(type(file_of_thing_to_decrypt))

try:
    file_in = open(priv_key_file, 'rb')
except FileNotFoundError:
    print(f"Whoops! We could not find the file {priv_key_file}. Are you sure it exists?")
else:
    
    try:
        private_key = RSA.import_key(open(file_of_thing_to_decrypt, encoding='latin1').read())
    except FileNotFoundError:
        print(f"Whoops! We could not find the file {file_of_thing_to_decrypt}. Are you sure it exists?")
    else:
        enc_session_key, nonce, tag, ciphertext = [file_in.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('Hooray! We have successfully decrypted it. Here it is:')
        print(data.decode('utf-8'))
        file_in.close()

错误开始发生在它说的地方,private_key = RSA.import_key(open(file_of_thing_to_decrypt, encoding='latin1').read()) 我收到了这个错误:

Traceback (most recent call last):
  File "C:/Users/Admin/AppData/Local/Programs/Python/Python36/Brandon Code/Doors Operating System/Some Pretty Handy Encryptions/RSA ULTIMATE PACK/decoding_system.py", line 19, in <module>
    private_key = RSA.import_key(open(file_of_thing_to_decrypt, encoding='latin1').read())
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\Crypto\PublicKey\RSA.py", line 785, in import_key
    raise ValueError("RSA key format is not supported")
ValueError: RSA key format is not supported

有人可以告诉我我做错了什么吗?

标签: pythonencryption

解决方案


推荐阅读