【问题标题】:pycrypto: unable to decrypt filepycrypto:无法解密文件
【发布时间】:2017-02-10 02:34:57
【问题描述】:

我正在使用 PKCS1_OAEP 加密算法来加密文件。文件加密成功但无法解密文件,报错“Ciphertext with wrong length.”

加密算法在这里:

#!/usr/bin/python
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import zlib
import base64


fd = open('test.doc', 'rb')
message = fd.read()
fd.close()

print "[*] Original File Size: %d" % len(message)

#message = 'To be encrypted'
key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_OAEP.new(key)

compressed = zlib.compress(message)
print "[*] Compressed File Size: %d" % len(compressed)

chunk_size = 128

ciphertext = ""
offset = 0

while offset < len(compressed):
    chunk = compressed[offset:offset+chunk_size]

    if len(chunk) % chunk_size != 0:
        chunk += " " * (chunk_size - len(chunk)) # Padding with spaces

    ciphertext += cipher.encrypt(chunk)
    offset += chunk_size

print "[*] Encrypted File Size: %d" % len(ciphertext)

encoded = ciphertext.encode("base64")

print "[*] Encoded file size: %d" % len(encoded)

fd = open("enc.data", 'wb')
fd.write(encoded)
fd.close()

print "[+] File saved successfully!"

解密算法来了:

#!/usr/bin/python
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import zlib
import base64

key = RSA.importKey(open('privkey.der').read())
cipher = PKCS1_OAEP.new(key)

fd = open('enc.data', 'rb')
encoded = fd.read().strip('\n')
fd.close()

decoded = encoded.decode("base64")


chunk_size = 128
offset = 0
plaintext = ""

while offset < len(decoded):
    plaintext += cipher.decrypt(decoded[offset:offset+chunk_size])
    offset += chunk_size

#plaintext = cipher.decrypt(decoded)

decompress = zlib.decompress(plaintext)


fd = open('decr.doc', 'wb')
fd.write(decompress)
fd.close()

使用以下脚本生成密钥

from Crypto.PublicKey import RSA 

new_key = RSA.generate(2048, e=65537) 
public_key = new_key.publickey().exportKey("PEM") 
private_key = new_key.exportKey("PEM") 


fileWrite(fileName, data):
    fd = open(fileName, 'wb')
    fd.write(data)
    fd.close()

fileWrite('privkey.der', private_key)
fileWrite('pubkey.der', public_key)

Here is the Error Message

【问题讨论】:

    标签: python encryption cryptography public-key-encryption pycrypto


    【解决方案1】:

    您使用 2048 位 RSA 密钥进行加密,该密钥提供 2048 位(256 字节)的加密块。您的解密实现假定加密块是 128 字节,实际上它们是 256 字节,因此您会收到“长度不正确”错误。请注意,您的加密文件大小 (64512) 是压缩文件大小 (32223) 的两倍多。

    一般来说,您不会将 RSA 用于 批量加密(因为它很慢),而是将它与像 AES这样的对称加密相结合>。然后,您将使用随机 AES 密钥加密数据,然后使用 RSA 密钥加密 AES 密钥。这样你就可以得到 AES 的速度和 RSA 的两个密钥。这被称为Hybrid Encryption

    【讨论】:

    • 感谢您的精彩建议,我稍后会尝试,但现在出于学习目的,我使用 RSA 加密数据。我已将块大小更改为 256,我要加密的文件大小为 21 个字节。现在我收到“明文太长”错误。 [链接] (imgur.com/a/VKiFi)
    • 每次加密的输出为 256 字节,但输入(使用您使用的 OAEP 填充)最大为 214 字节。所以你需要不同的块大小来输入和输出。
    • 谢谢先生 :) @Ebbe M.Pederse
    猜你喜欢
    • 2023-04-04
    • 2014-01-18
    • 2012-04-16
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多