使用Python-RSA加密消息时遭遇Overflow Exception错误求助
Hey there, let's break down why you're running into that Overflow Exception when using python-rsa, and how to fix it.
The Root Cause
That error almost always happens because your message is too long for the RSA key you're using. RSA with PKCS#1 v1.5 padding (the default in python-rsa) has a strict limit on plaintext length:
Maximum plaintext length = (key length in bytes) - 11
For example:
- A 1024-bit key allows max 128 - 11 = 117 bytes of encoded message
- A 2048-bit key allows 256 - 11 = 245 bytes
If your msg.encode() result exceeds this limit, the padding function (_pad_for_encryption) will throw an overflow error.
Solutions to Try
1. Verify Message vs. Key Length First
First, confirm your key's capacity and your message's size:
# Calculate your public key's byte length key_bytes_length = (pubkey.n.bit_length() + 7) // 8 max_plaintext_bytes = key_bytes_length - 11 # Check your message's encoded length message_bytes = msg.encode() print(f"Message length: {len(message_bytes)} bytes, max allowed: {max_plaintext_bytes} bytes")
If your message is longer than max_plaintext_bytes, you need to use a different approach (see below).
2. Use Hybrid Encryption (Recommended for Any Non-Tiny Message)
RSA was never designed to encrypt large data—this is a common misconception. The standard industry approach is hybrid encryption:
- Generate a random symmetric key (like AES-256, which handles large data efficiently)
- Encrypt your message with this symmetric key
- Encrypt the symmetric key with RSA
- Send the RSA-encrypted symmetric key + symmetrically encrypted message together
Here's a quick example (you'll need pycryptodome for AES):
import rsa from Crypto.Cipher import AES import os def encrypt_large_message(pubkey, message): # Generate a random AES-256 key aes_key = os.urandom(32) # Encrypt the message with AES (EAX mode provides built-in integrity check) cipher_aes = AES.new(aes_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(message.encode()) # Encrypt the AES key with RSA encrypted_aes_key = rsa.encrypt(aes_key, pubkey) # Return all components needed for decryption return encrypted_aes_key, cipher_aes.nonce, tag, ciphertext # Decryption counterpart (for reference) def decrypt_large_message(privkey, encrypted_aes_key, nonce, tag, ciphertext): aes_key = rsa.decrypt(encrypted_aes_key, privkey) cipher_aes = AES.new(aes_key, AES.MODE_EAX, nonce=nonce) return cipher_aes.decrypt_and_verify(ciphertext, tag).decode()
3. Double-Check Your Key Setup
If your message is definitely small enough but you still get the error:
- Make sure you're loading your public key correctly (e.g., using
rsa.PublicKey.load_pkcs1()for PEM-formatted keys, not mixing up public/private keys) - Verify compatibility between your Python 3.6 version and the python-rsa library—stick to versions like 4.5-4.7 (newer versions might drop support for Python 3.6)
内容的提问来源于stack exchange,提问作者Luís Duarte

