PyCryptodome脚本导入RSA私钥报密钥格式不支持错误,Shell运行正常求助
代码核心问题排查
- 触发当前
ValueError: RSA key format is not supported报错的直接原因是文件路径引用完全错位:
你定义的两个输入变量本身用途是清晰的:priv_key_file:用户输入的RSA私钥存储路径,应该用来读取、导入RSA密钥file_of_thing_to_decrypt:用户输入的加密文件路径,应该用来读取加密内容执行解密
但在导入私钥的代码行中,错将加密文件的路径作为读取源,把加密文件的二进制内容当成RSA私钥交给解析器识别,自然会因为内容格式不匹配抛出错误。
- 整体文件读取逻辑顺序混乱,就算修复路径错位的问题,后续解密步骤也会读错数据源:
代码中提前打开的file_in句柄绑定的是私钥文件,但后续代码却把这个句柄读取到的内容,当成加密会话密钥、nonce、标签、密文来解析,和加密流程的读写逻辑完全对调。 - 私钥读取的模式不兼容:
原代码用文本模式(带encoding='latin1')打开私钥文件,如果私钥是二进制DER格式存储,会直接触发解码错误。RSA.import_key本身支持直接接收二进制格式的密钥内容,用'rb'二进制模式打开私钥文件兼容性更强。
修正后的可运行代码
from Crypto.PublicKey import RSA from Crypto.Cipher import AES, PKCS1_OAEP from tkinter import Tk, 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') # 第一步:正确读取并导入RSA私钥 try: with open(priv_key_file, 'rb') as key_handler: private_key = RSA.import_key(key_handler.read()) except FileNotFoundError: print(f"Whoops! We could not find the file {priv_key_file}. Are you sure it exists?") except ValueError as e: print(f"Failed to parse RSA key: {e}") else: # 第二步:正确打开加密文件读取密文内容 try: with open(file_of_thing_to_decrypt, 'rb') as file_in: enc_session_key, nonce, tag, ciphertext = [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ] except FileNotFoundError: print(f"Whoops! We could not find the file {file_of_thing_to_decrypt}. Are you sure it exists?") else: # 执行解密流程 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'))
补充说明
之前你在Shell环境运行正常,是因为交互式执行时你会手动调整变量对应关系,逐行确认读取的文件和用途匹配;写成脚本后变量引用错位的问题就会直接暴露。
内容的提问来源于stack exchange,提问作者SSS-Says-Snek
相关产品推荐
相关产品推荐

