常常會出現如下情況:好不容易在網上找到了自己需要的資料,下載到電腦中是rar壓縮包格式的。解壓的時候卻需要密碼,沒有解壓密碼也只有望資料興嘆。
下面介紹一下使用python暴力破解rar壓縮格式的密碼。
我們主要用到的是rarfile庫中的extractall函數,大家可以自行百度搜索extractall函數的用法,這里不做過多介紹。
源代碼如下:
#############################################
#rar壓縮文件暴力破解程序
#版本:v1.0
#作者:世間小樹
#時間:2020.9.15
#############################################
import itertools
import string
import rarfile
import sys
path = "new.rar" #文件路徑
myrar = rarfile.RarFile(path,'r')
i=1
chars=string.digits+string.ascii_letters #密碼組成:數字+字母(包括大小寫)
def bruteforce(myrar,password):
"""強行破解密碼"""
try:
myrar.extractall(pwd=password.encode())
return True
except Exception as e:
print('嘗試密碼錯誤:',password)
return False
while i<=4: #密碼位數,不大於4位
passwords=itertools.product(chars,repeat=i)
for item in passwords:
pwd=''.join(item)
if bruteforce(myrar,pwd):
print("正確密碼是:"+pwd)
myrar.close()
sys.exit() #退出程序
i+=1