【问题标题】:Cannot recover original image file from encrypted file after decryption in Python3在 Python3 中解密后无法从加密文件中恢复原始图像文件
【发布时间】:2019-05-04 11:17:35
【问题描述】:

我正在编写一个脚本来使用 RSA 在 Python 中加密文件。我已成功加密原始文件并将其保存到另一个文件中。解密加密文件时,代码正在运行,但是当我打开图像时,它显示该文件不是.jpg 类型的文件。值 n、d 和 e 分别存储在 nfiledfileefile 中。

下面是加解密部分的代码:

 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是加密后生成的文件。 附图是我面临的错误

期待建议。

【问题讨论】:

    标签: python python-3.x encryption file-handling public-key-encryption


    【解决方案1】:

    您的 N 模数太小,无法直接加密消息。为此,N 至少需要与消息的比特一样长。具有一百万位左右的模数是非常不切实际的。我曾经尝试过 32786 位 RSA 密钥,当时需要一天时间才能生成一个密钥对。这就是为什么使用 AES 加密消息,然后使用 RSA 加密 AES 密钥的原因。 AES 密钥比消息小很多,所以几千位的密钥就足够了。

    【讨论】:

    • 但我认为错误在于我在加密和解密中将数据保存到文件中的方式
    • 当然,但您的加密函数也投射到一个子空间中,即使密钥已知,也无法从该子空间中唯一地恢复消息。任何陷门函数(如散列函数)都会发生同样的情况,输出不会唯一确定单个消息,而是注入映射到相同密文的一组消息。
    猜你喜欢
    • 1970-01-01
    • 2015-04-08
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多