Skip to main content
 首页 » 编程设计

Python IOError : Not a gzipped file (Gzip and Blowfish Encrypt/Compress) 错误

2025年05月04日23lori

我在使用 python 的内置库 gzip 时遇到了一些问题。浏览了几乎所有其他有关它的堆栈问题,但似乎都没有用。

我的问题是,当我尝试解压缩时,我得到了 IOError

我得到:

Traceback (most recent call last): 
File "mymodule.py", line 61, in 
  return gz.read() 
File "/usr/lib/python2.7/gzip.py", line 245, 
  readself._read(readsize) 
File "/usr/lib/python2.7/gzip.py", line 287, in 
  _readself._read_gzip_header() 
File "/usr/lib/python2.7/gzip.py", line 181, in 
  _read_gzip_header 
raise IOError, 'Not a gzipped file'IOError: Not a gzipped file 

这是我通过网络发送它的代码,我为什么这样做可能没有意义,但它通常在 while 循环和内存效率中,我只是简化了它。

buffer = cStringIO.StringIO(output) #output is from a subprocess call 
small_buffer = cStringIO.StringIO() 
small_string = buffer.read() #need a string to write to buffer  
gzip_obj = gzip.GzipFile(fileobj=small_buffer,compresslevel=6, mode='wb') 
gzip_obj.write(small_string) 
compressed_str = small_buffer.getvalue() 
 
blowfish = Blowfish.new('abcd', Blowfish.MODE_ECB) 
remainder = '|'*(8 - (len(compressed_str) % 8)) 
compressed_str += remainder 
encrypted = blowfish.encrypt(compressed_str) 
#i send it over smb, then retrieve it later 

然后这是检索它的代码:

#buffer is a cStringIO object filled with data from  retrieval 
decrypter = Blowfish.new('abcd', Blowfish.MODE_ECB) 
value = buffer.getvalue() 
decrypted = decrypter.decrypt(value) 
buff = cStringIO.StringIO(decrypted) 
buff.seek(0) 
gz = gzip.GzipFile(fileobj=buff) 
return gz.read() 

问题来了

返回 gz.read()

请您参考如下方法:

编辑: 我认为...您忘记在解压缩之前移除填充。下面的代码对我有用,如果我不删除填充,也会出现同样的错误。

编辑 2: 填充规范:我认为您进行填充的方式要求您传递填充的大小,因为我假设加密算法可以使用管道性格也。根据RFC 3852, Section 6.3 ,您应该使用所需填充字节数的二进制表示形式(不是 ASCII 数字)进行填充。我更新了下面的代码来解释规范。

import gzip 
import cStringIO 
from Crypto.Cipher import Blowfish 
 
#gzip and encrypt 
small_buffer = cStringIO.StringIO() 
small_string = "test data" 
with gzip.GzipFile(fileobj=small_buffer,compresslevel=6, mode='wb') as gzip_obj: 
    gzip_obj.write(small_string) 
compressed_str = small_buffer.getvalue() 
blowfish = Blowfish.new('better than bad') 
#remainder = '|'*(8 - (len(compressed_str) % 8)) 
pad_bytes = 8 - (len(compressed_str) % 8) 
padding = chr(pad_bytes)*pad_bytes 
compressed_str += padding 
encrypted = blowfish.encrypt(compressed_str) 
print("encrypted: {}".format(encrypted)) 
 
 
 
#decrypt and ungzip (pretending to be in a separate space here) 
value = encrypted 
blowfish = Blowfish.new('better than bad') 
decrypted = blowfish.decrypt(value) 
buff = cStringIO.StringIO(decrypted) 
buff.seek(-1,2) #move to the last byte 
pad_bytes = ord(buff.read(1)) #get the size of the padding from the last byte 
buff.truncate(len(buff.getvalue()) - pad_bytes) #probably a better way to do this. 
buff.seek(0) 
with gzip.GzipFile(fileobj=buff) as gz: 
    back_home = gz.read() 
print("back home: {}".format(back_home))