Skip to main content
 首页 » 编程设计

python之pycrypto:无法解密文件

2024年10月17日8shihaiming

我正在使用 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 .