如何用Python写一个暴力破解加密压缩包的程

发布网友

我来回答

2个回答

懂视网

基本原理在于Python标准库zipfile和扩展库unrar提供的解压缩方法extractall()可以指定密码,这样的话首先(手动或用程序)生成一个字典,然后依次尝试其中的密码,如果能够正常解压缩则表示密码正确。

import os
import sys
#zipfile是Python标准库
import zipfile
#尝试导入扩展库unrar,如果没有就临时安装
try:
 from unrar import rarfile
except:
 path = '"'+os.path.dirname(sys.executable)+'scriptspip" install --upgrade pip'
 os.system(path)
 path = '"'+os.path.dirname(sys.executable)+'scriptspip" install unrar'
 os.system(path)
 from unrar import rarfile

def decryptRarZipFile(filename):
 #根据文件扩展名,使用不同的库
 if filename.endswith('.zip'):
 fp = zipfile.ZipFile(filename)
 elif filename.endswith('.rar'):
 fp = rarfile.RarFile(filename)
 #解压缩的目标文件夹
 desPath = filename[:-4]
 if not os.path.exists(desPath):
 os.mkdir(desPath)
 #先尝试不用密码解压缩,如果成功则表示压缩文件没有密码
 try:
 fp.extractall(desPath)
 fp.close()
 print('No password')
 return
 #使用密码字典进行暴力破解
 except:
 try:
  fpPwd = open('pwddict.txt')
 except:
  print('No dict file pwddict.txt in current directory.')
  return
 for pwd in fpPwd:
  pwd = pwd.rstrip()
  try:
  if filename.endswith('.zip'):
   for file in fp.namelist():
   #对zip文件需要重新编码再解码,避免中文乱码
   fp.extract(file, path=desPath, pwd=pwd.encode())
   os.rename(desPath+''+file, desPath+''+file.encode('cp437').decode('gbk'))
   print('Success! ====>'+pwd)
   fp.close()
   break
  elif filename.endswith('.rar'):
   fp.extractall(path=desPath, pwd=pwd)
   print('Success! ====>'+pwd)
   fp.close()
   break
  except:
  pass
 fpPwd.close()

if __name__ == '__main__':
 filename = sys.argv[1]
 if os.path.isfile(filename) and filename.endswith(('.zip', '.rar')):
 decryptRarZipFile(filename)
 else:
 print('Must be Rar or Zip file')

更多Python相关技术文章,请访问Python教程栏目进行学习!

热心网友

有些时候加密rar软件经常会忘了密码,但记得密码的大概,于是乎用Python写个程序来暴力破解吧:
首先要搞清楚如何用命令行来解压缩,经研究,rar软件解压是用的unrar.exe,将这个程序拷贝到C:\windows,然后进入加密软件包所在的文件夹,用命令行运行 下面的命令:
unrar.exe e -pabcd 123.rar

程序就是先前拷到C:\windows,然后参数e是指相对路径,如果在是本文件夹下运行这个命令,则只打文件名就可以了,输入密码的方式是-p后面的字段,假定是abcd,最后面的是要解压的文件名。
下面我们解决如何用Python来运行windows下的命令行
import subprocess
command = 'unrar.exe e -n -pabcd 123.rar'
subprocess.call(command)

这样也可以完成解压,既然这样,那就开干吧,写一个暴力循环,我以4位字母为例,字母加的不全,实际使用可以视情况添加
list1=['a','b','c','d']
list2=['a','b','c','d']
list3=['a','b','c','d']
list4=['a','b','c','d']

for i1 in range(0,len(list1),1):
for i2 in range(0,len(list2),1):
for i3 in range(0, len(list3), 1):
for i4 in range(0, len(list4), 1):
password=list1[i1]+list2[i2]+list3[i3]+list4[i4]
print(password)
command = 'unrar.exe e -n -p' + password + ' 123.rar'
child = subprocess.call(command)
if child == 0:
print('解压密码是:',password)
break

child是返回值,为0表示解压成功,可以挑出循环并打印密码了,我实测,4位纯数字或者字母,只需要十多秒就出来了,非常简单

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com