gpt4 book ai didi

python - pycrypto:无法解密文件

转载 作者:太空宇宙 更新时间:2023-11-04 03:04:45 24 4
gpt4 key购买 nike

我正在使用 PKCS1_OAEP 加密算法来加密文件。文件加密成功,但无法解密文件,报错“Ciphertext with incorrect 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()

使用以下脚本生成 key

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

最佳答案

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

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

关于python - pycrypto:无法解密文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com