我正在尝试加密和解密 RSA 库文件。我总是成功加密,但在解密过程中出现溢出错误,出现异常,提示“OverflowError:消息需要 64 个字节,但只有 53 个字节的空间”,这是下面的代码;
import rsa
pubkey,privekey= rsa.newkeys(512)
path = "C:\\Users\\PC\\Documents\\Document.rtf"
with open (path,'rb') as thefile:
contents = thefile.read()
contents_encryp = rsa.encrypt(contents,pubkey)
with open(path, 'wb') as thefile:
thefile.write(contents_encryp)
下面是解密代码;
import rsa
from encryptor import contents_encryp,privekey
path = "C:\\Users\\PC\\Documents\\Document.rtf"
with open (path,'rb') as thefile:
contents = thefile.read()
contents_decryp = rsa.decrypt(contents_encryp,privekey)
with open(path, 'wb') as thefile:
thefile.write(contents_decryp)
我假设您正在使用 Python-RSA 模块(pip install rsa)。
文档明确指出:
RSA只能加密小于密钥的消息。随机填充会丢失几个字节,其余字节可用于消息本身。例如,512 位密钥可以编码 53 字节消息(512 位 = 64 字节,11 字节用于随机填充和其他内容)。
文档继续解释如何使用 AES 或其他分组密码来加密较大的文件。