pycrypto:无法解密文件

时间:2016-10-01 17:52:32

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

我正在使用PKCS1_OAEP加密算法来加密文件。文件已成功加密但无法解密文件,导致错误"密文长度不正确。"

加密算法在这里:

return $.when(grecaptcha.render(/* parameters */)
       , $("#recaptchaModal").modal('show').promise())

解密算法在这里:

#!/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()

Here is the Error Message

1 个答案:

答案 0 :(得分:1)

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

一般情况下,您不会将 RSA 用于批量加密(因为它非常慢),而是将其与等对称加密相结合AES 即可。然后,您将使用随机 AES 键对数据进行加密,然后使用 RSA 键加密 AES 键。这样您就可以获得 AES 的速度以及 RSA 的两个键。这称为Hybrid Encryption