我正在编写一个脚本来使用RSA加密Python中的文件。我已成功加密原始文件并将其保存到另一个文件。解密加密文件时,代码正在运行,但是当我打开图像时,它显示该文件不是.jpg
类型文件。值n,d和e分别存储在nfile
,dfile
和efile
中。
这是代码的加密和解密部分:
if myMode == 'encrypt':
n = open('nfile.pem', 'r')
e = open('efile.pem', 'r')
n1 = int(n.read())
e1 = int(e.read())
translated = str(pow(content1, e1, n1))
print(translated)
elif myMode == 'decrypt':
fileobj2 = open('encrypted.jpg', 'rb')
content2 = fileobj2.read
content3 = int.from_bytes(b'content2', byteorder='big')
fileobj2.close()
n = open('nfile.pem', 'r')
d = open('dfile.pem', 'r')
n1 = int(n.read())
d1 = int(d.read())
translated = str(pow(content3, d1, n1))
translated1 = str.encode(translated)
# Write out the translated message to the output file.
outputFileObj = open('decrypted1.jpg', 'wb')
outputFileObj.write(translated1)
outputFileObj.close()
这里,encrypted.jpg
是加密后生成的文件。附加的图像是我面临的错误
期待着建议。
您的N模数太小,无法直接加密消息。为了使其工作,N需要至少与位中的消息一样长。具有一百万左右比特的模数是非常不切实际的。我曾经花了一天生成一个密钥对,尝试过32786位RSA密钥。这就是使用AES加密消息的原因,然后使用RSA加密AES密钥。 AES密钥比消息小很多,因此具有几千位的密钥就足够了。