本周选做的信息安全实验为Python实现Zip文件的暴力破解

实验预备:
这次实验我们需要用到的库为zipfile。下来我们先来了解一下这个模块。
首先我们的重点是对zip文件的操作,而zipfile就是本次实验的核心。zipfile模块是python中自带的模块,提供了对zip文件的创建读、写、追加、解压以及列出zip文件列表的工具。这里我们主要用到ZipFile对象的extractall 方法来解压zip文件,现在我们看一下ZipFile的文档,在shell中运行Python交互环境,并使用help方法来查看模块的使用方法。


  `extractall(self, path=None, members=None, pwd=None)
     `Extract all members from the archive to the current working
     `directory. `path' specifies a different directory to extract to.
     `'members' is optional and must be a subset of the list returned
     `by namelist().

可以看到extractall(path=None, members=None, pwd=None)方法主要有三个参数,我们来看一下每个参数的含义:
•path指定解压后文件的存储位置
•members(可选)指定要Zip文件中要解压的文件,这个文件名称必须是通过namelist()方法返回列表的子集
•pwd指定Zip文件的解压密码

接下来尝试用程序解压带密码的压缩包。

!/usr/bin/env python

-- coding:utf-8 --


import zipfile

try:
   with zipfile.ZipFile('hello.zip') as zFile:
   zFile.extractall(path='./',pwd=b'123456')
   print('Extract successfully')
except:
   print('Extract faild')


第一次运行结果显示失败,查询代码,原来是解压密码错误,修改代码,重新解压,成功。

接下来我们尝试用密码暴力破解,给订指定的密码字典,逐条尝试,直到成破解。


import zipfile
zFile = zipfile.ZipFile("hello.zip");
passFile = open('./pass.txt');
for line in passFile.readlines():
    password = line.strip('\n');
    try:
        zFile.extractall(path="./",pwd=password);
        print("当前测试密码为:"+password+"  密码正确!!!");
	break;
        exit(0);
    except:
        print("当前测试密码为:"+password+"  密码错误!!!");
        pass;

开始进行暴力破解。。。。

破解成功!
鉴于前两个代码都是简单的知道密码和从已知的密码序列中查找,不符合暴力破解的定义,于是在网上查询资料,理解后对其进行修改得出下列代码。


 import random
import zipfile
class Dictor():
    CSet=‘0123456789'\
    'abcdefghijklmnopqrstuvwxyz'\
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\
    '~!@#$%^&*()_+’
    def __init__(self,minlen,maxlen):
        if maxlen>minlen:
            self.__minlen=minlen
            self.__maxlen=maxlen
        else:
            self.__minlen=maxlen
            self.__maxlen=minlen
    def __iter__(self):
        return self
    def next(self):
        ret=''
        for i in range(0,random.randrange(self.__minlen,self.__maxlen+1)):
            ret+=random.choice(Dictor.CSet)
        return ret
if __name__=='__main__':
     zFile = zipfile.ZipFile("hello.zip");
     for str in Dictor(5,6):
        try:
           zFile.extractall(path="./",pwd=str)
           print("当前测试密码为:"+str+"  密码正确!!!")
           break
	except:
           print("当前测试密码为:"+str+"  密码错误!!!");
           pass

这段代码自带密码生成器,可以自动根据给出得范围进行全排列进而生成新密码进行解压测试。
效果图:

从测试中可得,密码破解得结果。

posted on 2016-12-06 20:43  唐宋5231  阅读(138)  评论(0编辑  收藏  举报