【问题标题】:Create password protected zip file? [duplicate]创建密码保护的zip文件Python [重复]
【发布时间】:2018-05-12 20:31:57
【问题描述】:

我正在使用以下代码在我的 Python34 应用程序中使用 zipFile 从用户上传的文件创建受密码保护的 zip 文件。但是当我从 Windows 打开 zip 文件时,它不会要求输入密码。稍后我将使用相同的密码从 python 读取 zip 文件。我做错了什么?

这是我的代码:

pwdZipFilePath = uploadFilePath + "encryptedZipFiles/"
filePath = uploadFilePath

if not os.path.exists(pwdZipFilePath):        
      os.makedirs(pwdZipFilePath)

#save csv file to a path
fd, filePath = tempfile.mkstemp(suffix=source.name, dir=filePath)

with open(filePath, 'wb') as dest:
    shutil.copyfileobj(source, dest)

#convert that csv to zip
fd, pwdZipFilePath = tempfile.mkstemp(suffix=source.name + ".zip", dir=pwdZipFilePath)

with zipfile.ZipFile(pwdZipFilePath, 'w') as myzip:
    myzip.write(filePath)

    myzip.setpassword(b"tipi")

【问题讨论】:

  • 你真的可以访问文件文件吗?还是只是将其可视化?这是 zip 密码保护中的常见行为,即使文件受密码保护,您实际上也可以看到文件。
  • @user1767754 是的,我也可以访问 zip 中的文件。我什至打开了它。如果它仍然要打开它,设置密码有什么意义?
  • @Galen 我不这么认为。我已经检查了这个网站上的所有相关问题,但仍然有问题。

标签: python django python-3.x zipfile


【解决方案1】:

documentation for zipfile 表示ZipFile.setpassword 设置“提取加密文件的默认密码”。

在文档的最顶部:“它支持解密 ZIP 存档中的加密文件,但目前无法创建加密文件。”

编辑: 要创建受密码保护的 ZIP 文件,请尝试使用 pyminizip 之类的包。

【讨论】:

  • 好的,那么如何在 python 中创建受密码保护的 zip 文件?我咨询了其他解决方案,但没有任何帮助。
  • @TahreemIqbal 我会看像pyminizip这样的包。
  • 好的,我会调查的。谢谢
  • 我一开始以为他是在写文件,然后设置密码,但震惊地意识到 setpassword 有点蹩脚。但是在一些参考书目python in a nutshell 中,他们展示了他们如何使用setpassword 来防止字典攻击。
  • zipfile 的文档说:'它支持解密 ZIP 档案中的加密文件,但目前无法创建加密文件。解密非常慢,因为它是在本机 Python 而不是 C 中实现的。 - 这个模块适合吗?
【解决方案2】:

内置的zipfile 模块不支持写入密码加密文件(仅读取)。你可以使用pyminizip:

import pyminizip
pyminizip.compress("dummy.txt", "myzip.zip", "noneshallpass", compression_level)

或者,如果您使用的是 Windows/msysgit,并且不知道格式:

import os
os.system('tar cz dummy.txt | openssl enc -aes-256-cbc -e -k noneshallpass > mypacked.enc')
os.remove('dummy.txt')
os.system('openssl enc -aes-256-cbc -d -k noneshallpass -in mypacked.enc | tar xz')

【讨论】:

  • 我刚看了setPassword,过了一会才发现这是写之前的设置。
  • @user1767754 你根本没读过。请参阅Galen 的回答。
  • 其实我的意思是相反的before reading 并想强调的是,阅读时的第一个期望是,您可以设置压缩文件的密码,而不是在阅读时应用密码。
  • can't install pyminizip on windows.: "error: Microsoft Visual C++ 9.0 is required. Get it from aka.ms/vcpython27"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 2010-11-09
  • 2022-08-10
相关资源
最近更新 更多