bruteforce / app.py
COLTO50's picture
Update app.py
7fa8436 verified
raw
history blame
No virus
7.39 kB
import gradio as gr
import itertools
import string
import time
import multiprocessing
import math
import zxcvbn
import hashlib
import random
def generate_passwords(chars, length, start, end):
for attempt in itertools.islice(itertools.product(chars, repeat=length), start, end):
yield ''.join(attempt)
def crack_chunk(args):
chars, length, start, end, password_hash, hash_function, chunk_id, progress_queue = args
attempts = 0
for attempt in generate_passwords(chars, length, start, end):
attempts += 1
if attempts % 1000000 == 0:
progress_queue.put((chunk_id, attempts))
if hash_function(attempt.encode()).hexdigest() == password_hash:
progress_queue.put((chunk_id, attempts))
return attempts, attempt
progress_queue.put((chunk_id, attempts))
return attempts, None
def optimized_brute_force(password, hash_type='sha256', use_common_passwords=True, use_dictionary=True, progress=gr.Progress()):
start_time = time.time()
total_attempts = 0
chars = string.ascii_letters + string.digits + string.punctuation
cpu_count = multiprocessing.cpu_count()
hash_function = getattr(hashlib, hash_type)
password_hash = hash_function(password.encode()).hexdigest()
# Feature 1: Common password check
if use_common_passwords:
common_passwords = ['123456', 'password', 'qwerty', 'admin', '123456789', '12345', '1234', '12345678', '111111', '1234567']
for common_pwd in common_passwords:
total_attempts += 1
if hash_function(common_pwd.encode()).hexdigest() == password_hash:
end_time = time.time()
return create_result_output(common_pwd, total_attempts, start_time, end_time, password)
# Feature 2: Dictionary attack
if use_dictionary:
with open('english_words.txt', 'r') as f:
dictionary_words = f.read().splitlines()
for word in dictionary_words:
total_attempts += 1
if hash_function(word.encode()).hexdigest() == password_hash:
end_time = time.time()
return create_result_output(word, total_attempts, start_time, end_time, password)
for length in range(1, len(password) + 1):
chunk_size = math.ceil(len(chars) ** length / cpu_count)
manager = multiprocessing.Manager()
progress_queue = manager.Queue()
chunks = [
(chars, length, i * chunk_size, (i + 1) * chunk_size, password_hash, hash_function, i, progress_queue)
for i in range(cpu_count)
]
with multiprocessing.Pool(processes=cpu_count) as pool:
results = pool.map_async(crack_chunk, chunks)
chunk_progress = [0] * cpu_count
while not results.ready():
while not progress_queue.empty():
chunk_id, attempts = progress_queue.get()
chunk_progress[chunk_id] = attempts
total_attempts = sum(chunk_progress)
progress(total_attempts, desc=f"Trying {length}-character passwords")
time.sleep(0.1)
results = results.get()
for attempts, cracked in results:
total_attempts += attempts
if cracked:
end_time = time.time()
return create_result_output(cracked, total_attempts, start_time, end_time, password)
end_time = time.time()
return create_result_output(None, total_attempts, start_time, end_time, password)
def create_result_output(cracked_password, attempts, start_time, end_time, original_password):
time_taken = round((end_time - start_time) * 1000, 2)
output = []
if cracked_password:
output.append(f"Password cracked: {cracked_password}")
else:
output.append("Password not found")
output.append(f"Attempts: {attempts:,}")
output.append(f"Time taken: {time_taken} ms")
# Feature 3: Password strength evaluation
strength = zxcvbn.zxcvbn(original_password)
output.append(f"Password strength score: {strength['score']}/4")
output.append(f"Estimated guesses: {strength['guesses']:,}")
# Feature 4: Entropy calculation
entropy = calculate_entropy(original_password)
output.append(f"Password entropy: {entropy:.2f} bits")
# Feature 5: Suggestions for improvement
if strength['score'] < 3:
output.append("Suggestions for improvement:")
for suggestion in strength['feedback']['suggestions']:
output.append(f"- {suggestion}")
return "\n".join(output)
def calculate_entropy(password):
char_set = set(password)
return len(password) * math.log2(len(char_set))
def generate_password(length=12, complexity='medium'):
if complexity == 'low':
chars = string.ascii_lowercase + string.digits
elif complexity == 'medium':
chars = string.ascii_letters + string.digits
else:
chars = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(chars) for _ in range(length))
def brute_force_interface(password, hash_type='sha256', use_common_passwords=True, use_dictionary=True):
return optimized_brute_force(password, hash_type, use_common_passwords, use_dictionary)
def analyze_password(password):
strength = zxcvbn.zxcvbn(password)
entropy = calculate_entropy(password)
output = [
f"Password strength score: {strength['score']}/4",
f"Estimated guesses: {strength['guesses']:,}",
f"Password entropy: {entropy:.2f} bits",
]
if strength['score'] < 3:
output.append("Suggestions for improvement:")
for suggestion in strength['feedback']['suggestions']:
output.append(f"- {suggestion}")
return "\n".join(output)
iface = gr.Interface(
fn=brute_force_interface,
inputs=[
gr.Textbox(label="Enter password to crack"),
gr.Dropdown(choices=['md5', 'sha1', 'sha256', 'sha512'], label="Hash type", value='sha256'),
gr.Checkbox(label="Use common passwords", value=True),
gr.Checkbox(label="Use dictionary attack", value=True),
],
outputs="text",
title="Advanced Brute-Force Password Cracker Simulator",
description="This simulator attempts to crack a given password using various methods. It utilizes multiple CPU cores for faster cracking. Note: This is for educational purposes only.",
)
password_analyzer = gr.Interface(
fn=analyze_password,
inputs=gr.Textbox(label="Enter password to analyze"),
outputs="text",
title="Password Strength Analyzer",
description="Analyze the strength of a given password without attempting to crack it.",
)
password_generator = gr.Interface(
fn=generate_password,
inputs=[
gr.Slider(minimum=8, maximum=32, step=1, label="Password Length", value=12),
gr.Dropdown(choices=['low', 'medium', 'high'], label="Complexity", value='medium'),
],
outputs=gr.Textbox(label="Generated Password"),
title="Secure Password Generator",
description="Generate a secure password based on specified length and complexity.",
)
demo = gr.TabbedInterface([iface, password_analyzer, password_generator], ["Brute-Force Simulator", "Password Analyzer", "Password Generator"])
if __name__ == "__main__":
demo.launch()