import hashlib import itertools import string import time import json import os import pickle from datetime import datetime class HashFinder: def __init__(self, target_hash, state_file="hash_finder_state.pkl", log_file="attempts_log.json"): self.target_hash = target_hash.lower() self.state_file = state_file self.log_file = log_file self.found_word = None self.attempts = 0 self.start_time = None self.current_state = { 'char_set_index': 0, 'current_length': 1, 'current_index': 0, 'completed_lengths': [], 'attempted_words': set(), 'char_sets_tried': [] } # Character sets to try (in order of complexity) self.char_sets = [ (string.ascii_lowercase, "lowercase letters"), (string.digits, "digits"), (string.ascii_lowercase + string.digits, "lowercase + digits"), (string.ascii_letters, "all letters"), (string.ascii_letters + string.digits, "letters + digits"), (string.ascii_letters + string.digits + string.punctuation, "all printable") ] # Common words to try first self.common_words = [ "password", "123456", "admin", "qwerty", "letmein", "welcome", "monkey", "password1", "12345678", "123456789", "baseball", "football", "abc123", "hello", "world", "test", "secret", "key", "value", "data", "string", "python", "code", "program", "hash", "crypto", "sha256", "algorithm", "example", "sample", "demo", "input", "output", "result", "find", "compute", "calculate", "generate", "create", "search", "locate", "word", "text", "message", "information", "security", "encryption", "target", "brute", "force", "crack", "match", "seek", "hunt", "discover", "uncover", "reveal", "detect", "identify", "solve" ] def sha256_hash(self, text): """Calculate SHA256 hash of a string""" return hashlib.sha256(text.encode('utf-8')).hexdigest() def save_state(self): """Save current state to file""" state_data = { 'target_hash': self.target_hash, 'found_word': self.found_word, 'attempts': self.attempts, 'start_time': self.start_time, 'current_state': self.current_state, 'timestamp': datetime.now().isoformat() } with open(self.state_file, 'wb') as f: pickle.dump(state_data, f) print(f"State saved to {self.state_file}") def load_state(self): """Load state from file if it exists""" if os.path.exists(self.state_file): try: with open(self.state_file, 'rb') as f: state_data = pickle.load(f) if state_data['target_hash'] == self.target_hash: self.found_word = state_data['found_word'] self.attempts = state_data['attempts'] self.start_time = state_data['start_time'] self.current_state = state_data['current_state'] print(f"Loaded previous state: {self.attempts:,} attempts") return True else: print("State file contains different target hash. Starting fresh.") except Exception as e: print(f"Error loading state: {e}. Starting fresh.") return False def log_attempt(self, word, hash_value, found=False): """Log an attempt to JSON file""" log_entry = { 'timestamp': datetime.now().isoformat(), 'word': word, 'hash': hash_value, 'found': found, 'attempt_number': self.attempts } # Read existing log log_data = [] if os.path.exists(self.log_file): try: with open(self.log_file, 'r') as f: log_data = json.load(f) except: pass # Add new entry log_data.append(log_entry) # Write back with open(self.log_file, 'w') as f: json.dump(log_data, f, indent=2) def try_common_words(self): """Try common words first""" print("Phase 1: Trying common words...") for i, word in enumerate(self.common_words): if word in self.current_state['attempted_words']: continue hash_value = self.sha256_hash(word) self.attempts += 1 self.current_state['attempted_words'].add(word) self.log_attempt(word, hash_value) if hash_value == self.target_hash: self.found_word = word print(f"\n✓ Found in common words: '{word}'") return True # Show progress if (i + 1) % 10 == 0: print(f" Checked {i + 1}/{len(self.common_words)} common words...") print("Not found in common words.") return False def brute_force_with_resume(self, max_length=8): """Brute force search with resume capability""" if self.start_time is None: # Start from saved state or beginning char_set_index = self.current_state['char_set_index'] current_length = self.current_state['current_length'] current_index = self.current_state['current_index'] char_set, desc = self.char_sets[cs_index] if cs_index in self.current_state['char_sets_tried']: continue print(f"\nTrying {desc} (character set {cs_index + 1}/{len(self.char_sets)})...") if length in self.current_state['completed_lengths']: continue # Calculate total combinations for progress total_combinations = len(char_set) ** length combinations_checked = 0 # Generate combinations starting from saved index for i, attempt in enumerate(itertools.product(char_set, repeat=length)): if i < current_index: continue # Skip if already attempted if word in self.current_state['attempted_words']: continue hash_value = self.sha256_hash(word) self.attempts += 1 self.current_state['attempted_words'].add(word) self.log_attempt(word, hash_value) # Update current state self.current_state['char_set_index'] = cs_index self.current_state['current_length'] = length self.current_state['current_index'] = i + 1 # Show progress combinations_checked += 1 if combinations_checked % 10000 == 0: rate = self.attempts / elapsed if elapsed > 0 else 0 # Auto-save every 10,000 attempts if combinations_checked % 100000 == 0: self.save_state() # Check if found if hash_value == self.target_hash: self.found_word = word self.log_attempt(word, hash_value, found=True) return True # Completed this length print(f" ({combinations_checked:,} combinations)") self.current_state['completed_lengths'].append(length) self.current_state['current_index'] = 0 self.save_state() # Completed this character set self.current_state['char_sets_tried'].append(cs_index) self.current_state['current_length'] = 1 self.save_state() return False def display_stats(self): """Display current statistics""" if self.start_time: rate = self.attempts / elapsed if elapsed > 0 else 0 print(f"\nStatistics:") print(f" Total attempts: {self.attempts:,}") print(f" Time elapsed: {elapsed:.2f} seconds") print(f" Hash rate: {rate:,.0f} hashes/sec") print(f" State file: {self.state_file}") print(f" Log file: {self.log_file}") def verify_result(self): """Verify the found word""" if self.found_word: actual_hash = self.sha256_hash(self.found_word) print("\n" + "=" * 60) print("VERIFICATION:") print(f"Word: '{self.found_word}'") print(f"Expected SHA256: {self.target_hash}") print(f"Actual SHA256: {actual_hash}") print(f"Match: {actual_hash == self.target_hash}") print("=" * 60) return actual_hash == self.target_hash return False def cleanup(self): """Clean up state file if search is complete""" if self.found_word and os.path.exists(self.state_file): os.remove(self.state_file) print(f"State file {self.state_file} removed.") def main(): target_hash = "86f61bf1bc1fe799467b9a3220d7559941bd849c783395e554b101241cc2f46a" print("SHA256 Hash Word Finder with Resume/Pause") print("=" * 60) print(f"Target: {target_hash}") print("Press Ctrl+C to pause and save progress") print("=" * 60) # Initialize finder finder = HashFinder(target_hash) try: # Try to load previous state state_loaded = finder.load_state() if state_loaded and finder.found_word: print("Previous successful search found!") finder.verify_result() return # Start search if not finder.found_word: if not state_loaded or not finder.try_common_words(): print("\nStarting/Resuming brute force search...") found = finder.brute_force_with_resume(max_length=6) if found: print(f"\n✓ SUCCESS! Found: '{finder.found_word}'") else: print(f"\n✗ Not found with current parameters.") # Display final stats finder.display_stats() # Verify result if finder.found_word: finder.verify_result() finder.cleanup() except KeyboardInterrupt: print("\n\n⏸️ Search paused by user") finder.save_state() finder.display_stats() print("You can resume later by running the program again.") except Exception as e: print(f"\n❌ Error: {e}") finder.save_state() print("Progress saved. You can resume later.") if __name__ == "__main__": main()
Standard input is empty
import hashlib
import itertools
import string
import time
import json
import os
import pickle
from datetime import datetime
class HashFinder:
def __init__(self, target_hash, state_file="hash_finder_state.pkl", log_file="attempts_log.json"):
self.target_hash = target_hash.lower()
self.state_file = state_file
self.log_file = log_file
self.found_word = None
self.attempts = 0
self.start_time = None
self.current_state = {
'char_set_index': 0,
'current_length': 1,
'current_index': 0,
'completed_lengths': [],
'attempted_words': set(),
'char_sets_tried': []
}
# Character sets to try (in order of complexity)
self.char_sets = [
(string.ascii_lowercase, "lowercase letters"),
(string.digits, "digits"),
(string.ascii_lowercase + string.digits, "lowercase + digits"),
(string.ascii_letters, "all letters"),
(string.ascii_letters + string.digits, "letters + digits"),
(string.ascii_letters + string.digits + string.punctuation, "all printable")
]
# Common words to try first
self.common_words = [
"password", "123456", "admin", "qwerty", "letmein", "welcome", "monkey",
"password1", "12345678", "123456789", "baseball", "football", "abc123",
"hello", "world", "test", "secret", "key", "value", "data", "string",
"python", "code", "program", "hash", "crypto", "sha256", "algorithm",
"example", "sample", "demo", "input", "output", "result", "find",
"compute", "calculate", "generate", "create", "search", "locate",
"word", "text", "message", "information", "security", "encryption",
"target", "brute", "force", "crack", "match", "seek", "hunt",
"discover", "uncover", "reveal", "detect", "identify", "solve"
]
def sha256_hash(self, text):
"""Calculate SHA256 hash of a string"""
return hashlib.sha256(text.encode('utf-8')).hexdigest()
def save_state(self):
"""Save current state to file"""
state_data = {
'target_hash': self.target_hash,
'found_word': self.found_word,
'attempts': self.attempts,
'start_time': self.start_time,
'current_state': self.current_state,
'timestamp': datetime.now().isoformat()
}
with open(self.state_file, 'wb') as f:
pickle.dump(state_data, f)
print(f"State saved to {self.state_file}")
def load_state(self):
"""Load state from file if it exists"""
if os.path.exists(self.state_file):
try:
with open(self.state_file, 'rb') as f:
state_data = pickle.load(f)
if state_data['target_hash'] == self.target_hash:
self.found_word = state_data['found_word']
self.attempts = state_data['attempts']
self.start_time = state_data['start_time']
self.current_state = state_data['current_state']
print(f"Loaded previous state: {self.attempts:,} attempts")
return True
else:
print("State file contains different target hash. Starting fresh.")
except Exception as e:
print(f"Error loading state: {e}. Starting fresh.")
return False
def log_attempt(self, word, hash_value, found=False):
"""Log an attempt to JSON file"""
log_entry = {
'timestamp': datetime.now().isoformat(),
'word': word,
'hash': hash_value,
'found': found,
'attempt_number': self.attempts
}
# Read existing log
log_data = []
if os.path.exists(self.log_file):
try:
with open(self.log_file, 'r') as f:
log_data = json.load(f)
except:
pass
# Add new entry
log_data.append(log_entry)
# Write back
with open(self.log_file, 'w') as f:
json.dump(log_data, f, indent=2)
def try_common_words(self):
"""Try common words first"""
print("Phase 1: Trying common words...")
for i, word in enumerate(self.common_words):
if word in self.current_state['attempted_words']:
continue
hash_value = self.sha256_hash(word)
self.attempts += 1
self.current_state['attempted_words'].add(word)
self.log_attempt(word, hash_value)
if hash_value == self.target_hash:
self.found_word = word
print(f"\n✓ Found in common words: '{word}'")
return True
# Show progress
if (i + 1) % 10 == 0:
print(f" Checked {i + 1}/{len(self.common_words)} common words...")
print("Not found in common words.")
return False
def brute_force_with_resume(self, max_length=8):
"""Brute force search with resume capability"""
if self.start_time is None:
self.start_time = time.time()
# Start from saved state or beginning
char_set_index = self.current_state['char_set_index']
current_length = self.current_state['current_length']
current_index = self.current_state['current_index']
for cs_index in range(char_set_index, len(self.char_sets)):
char_set, desc = self.char_sets[cs_index]
if cs_index in self.current_state['char_sets_tried']:
continue
print(f"\nTrying {desc} (character set {cs_index + 1}/{len(self.char_sets)})...")
for length in range(current_length, max_length + 1):
if length in self.current_state['completed_lengths']:
continue
print(f" Length {length}: ", end="", flush=True)
# Calculate total combinations for progress
total_combinations = len(char_set) ** length
combinations_checked = 0
# Generate combinations starting from saved index
for i, attempt in enumerate(itertools.product(char_set, repeat=length)):
if i < current_index:
continue
word = ''.join(attempt)
# Skip if already attempted
if word in self.current_state['attempted_words']:
continue
hash_value = self.sha256_hash(word)
self.attempts += 1
self.current_state['attempted_words'].add(word)
self.log_attempt(word, hash_value)
# Update current state
self.current_state['char_set_index'] = cs_index
self.current_state['current_length'] = length
self.current_state['current_index'] = i + 1
# Show progress
combinations_checked += 1
if combinations_checked % 10000 == 0:
elapsed = time.time() - self.start_time
rate = self.attempts / elapsed if elapsed > 0 else 0
print(".", end="", flush=True)
# Auto-save every 10,000 attempts
if combinations_checked % 100000 == 0:
self.save_state()
# Check if found
if hash_value == self.target_hash:
self.found_word = word
self.log_attempt(word, hash_value, found=True)
return True
# Completed this length
print(f" ({combinations_checked:,} combinations)")
self.current_state['completed_lengths'].append(length)
self.current_state['current_index'] = 0
self.save_state()
# Completed this character set
self.current_state['char_sets_tried'].append(cs_index)
self.current_state['current_length'] = 1
self.save_state()
return False
def display_stats(self):
"""Display current statistics"""
if self.start_time:
elapsed = time.time() - self.start_time
rate = self.attempts / elapsed if elapsed > 0 else 0
print(f"\nStatistics:")
print(f" Total attempts: {self.attempts:,}")
print(f" Time elapsed: {elapsed:.2f} seconds")
print(f" Hash rate: {rate:,.0f} hashes/sec")
print(f" State file: {self.state_file}")
print(f" Log file: {self.log_file}")
def verify_result(self):
"""Verify the found word"""
if self.found_word:
actual_hash = self.sha256_hash(self.found_word)
print("\n" + "=" * 60)
print("VERIFICATION:")
print(f"Word: '{self.found_word}'")
print(f"Expected SHA256: {self.target_hash}")
print(f"Actual SHA256: {actual_hash}")
print(f"Match: {actual_hash == self.target_hash}")
print("=" * 60)
return actual_hash == self.target_hash
return False
def cleanup(self):
"""Clean up state file if search is complete"""
if self.found_word and os.path.exists(self.state_file):
os.remove(self.state_file)
print(f"State file {self.state_file} removed.")
def main():
target_hash = "86f61bf1bc1fe799467b9a3220d7559941bd849c783395e554b101241cc2f46a"
print("SHA256 Hash Word Finder with Resume/Pause")
print("=" * 60)
print(f"Target: {target_hash}")
print("Press Ctrl+C to pause and save progress")
print("=" * 60)
# Initialize finder
finder = HashFinder(target_hash)
try:
# Try to load previous state
state_loaded = finder.load_state()
if state_loaded and finder.found_word:
print("Previous successful search found!")
finder.verify_result()
return
# Start search
if not finder.found_word:
if not state_loaded or not finder.try_common_words():
print("\nStarting/Resuming brute force search...")
found = finder.brute_force_with_resume(max_length=6)
if found:
print(f"\n✓ SUCCESS! Found: '{finder.found_word}'")
else:
print(f"\n✗ Not found with current parameters.")
# Display final stats
finder.display_stats()
# Verify result
if finder.found_word:
finder.verify_result()
finder.cleanup()
except KeyboardInterrupt:
print("\n\n⏸️ Search paused by user")
finder.save_state()
finder.display_stats()
print("You can resume later by running the program again.")
except Exception as e:
print(f"\n❌ Error: {e}")
finder.save_state()
print("Progress saved. You can resume later.")
if __name__ == "__main__":
main()