fork download
  1. import hashlib
  2. import itertools
  3. import string
  4. import time
  5. import json
  6. import os
  7. import pickle
  8. from datetime import datetime
  9.  
  10. class HashFinder:
  11. def __init__(self, target_hash, state_file="hash_finder_state.pkl", log_file="attempts_log.json"):
  12. self.target_hash = target_hash.lower()
  13. self.state_file = state_file
  14. self.log_file = log_file
  15. self.found_word = None
  16. self.attempts = 0
  17. self.start_time = None
  18. self.current_state = {
  19. 'char_set_index': 0,
  20. 'current_length': 1,
  21. 'current_index': 0,
  22. 'completed_lengths': [],
  23. 'attempted_words': set(),
  24. 'char_sets_tried': []
  25. }
  26.  
  27. # Character sets to try (in order of complexity)
  28. self.char_sets = [
  29. (string.ascii_lowercase, "lowercase letters"),
  30. (string.digits, "digits"),
  31. (string.ascii_lowercase + string.digits, "lowercase + digits"),
  32. (string.ascii_letters, "all letters"),
  33. (string.ascii_letters + string.digits, "letters + digits"),
  34. (string.ascii_letters + string.digits + string.punctuation, "all printable")
  35. ]
  36.  
  37. # Common words to try first
  38. self.common_words = [
  39. "password", "123456", "admin", "qwerty", "letmein", "welcome", "monkey",
  40. "password1", "12345678", "123456789", "baseball", "football", "abc123",
  41. "hello", "world", "test", "secret", "key", "value", "data", "string",
  42. "python", "code", "program", "hash", "crypto", "sha256", "algorithm",
  43. "example", "sample", "demo", "input", "output", "result", "find",
  44. "compute", "calculate", "generate", "create", "search", "locate",
  45. "word", "text", "message", "information", "security", "encryption",
  46. "target", "brute", "force", "crack", "match", "seek", "hunt",
  47. "discover", "uncover", "reveal", "detect", "identify", "solve"
  48. ]
  49.  
  50. def sha256_hash(self, text):
  51. """Calculate SHA256 hash of a string"""
  52. return hashlib.sha256(text.encode('utf-8')).hexdigest()
  53.  
  54. def save_state(self):
  55. """Save current state to file"""
  56. state_data = {
  57. 'target_hash': self.target_hash,
  58. 'found_word': self.found_word,
  59. 'attempts': self.attempts,
  60. 'start_time': self.start_time,
  61. 'current_state': self.current_state,
  62. 'timestamp': datetime.now().isoformat()
  63. }
  64.  
  65. with open(self.state_file, 'wb') as f:
  66. pickle.dump(state_data, f)
  67.  
  68. print(f"State saved to {self.state_file}")
  69.  
  70. def load_state(self):
  71. """Load state from file if it exists"""
  72. if os.path.exists(self.state_file):
  73. try:
  74. with open(self.state_file, 'rb') as f:
  75. state_data = pickle.load(f)
  76.  
  77. if state_data['target_hash'] == self.target_hash:
  78. self.found_word = state_data['found_word']
  79. self.attempts = state_data['attempts']
  80. self.start_time = state_data['start_time']
  81. self.current_state = state_data['current_state']
  82. print(f"Loaded previous state: {self.attempts:,} attempts")
  83. return True
  84. else:
  85. print("State file contains different target hash. Starting fresh.")
  86. except Exception as e:
  87. print(f"Error loading state: {e}. Starting fresh.")
  88.  
  89. return False
  90.  
  91. def log_attempt(self, word, hash_value, found=False):
  92. """Log an attempt to JSON file"""
  93. log_entry = {
  94. 'timestamp': datetime.now().isoformat(),
  95. 'word': word,
  96. 'hash': hash_value,
  97. 'found': found,
  98. 'attempt_number': self.attempts
  99. }
  100.  
  101. # Read existing log
  102. log_data = []
  103. if os.path.exists(self.log_file):
  104. try:
  105. with open(self.log_file, 'r') as f:
  106. log_data = json.load(f)
  107. except:
  108. pass
  109.  
  110. # Add new entry
  111. log_data.append(log_entry)
  112.  
  113. # Write back
  114. with open(self.log_file, 'w') as f:
  115. json.dump(log_data, f, indent=2)
  116.  
  117. def try_common_words(self):
  118. """Try common words first"""
  119. print("Phase 1: Trying common words...")
  120.  
  121. for i, word in enumerate(self.common_words):
  122. if word in self.current_state['attempted_words']:
  123. continue
  124.  
  125. hash_value = self.sha256_hash(word)
  126. self.attempts += 1
  127. self.current_state['attempted_words'].add(word)
  128. self.log_attempt(word, hash_value)
  129.  
  130. if hash_value == self.target_hash:
  131. self.found_word = word
  132. print(f"\n✓ Found in common words: '{word}'")
  133. return True
  134.  
  135. # Show progress
  136. if (i + 1) % 10 == 0:
  137. print(f" Checked {i + 1}/{len(self.common_words)} common words...")
  138.  
  139. print("Not found in common words.")
  140. return False
  141.  
  142. def brute_force_with_resume(self, max_length=8):
  143. """Brute force search with resume capability"""
  144. if self.start_time is None:
  145. self.start_time = time.time()
  146.  
  147. # Start from saved state or beginning
  148. char_set_index = self.current_state['char_set_index']
  149. current_length = self.current_state['current_length']
  150. current_index = self.current_state['current_index']
  151.  
  152. for cs_index in range(char_set_index, len(self.char_sets)):
  153. char_set, desc = self.char_sets[cs_index]
  154.  
  155. if cs_index in self.current_state['char_sets_tried']:
  156. continue
  157.  
  158. print(f"\nTrying {desc} (character set {cs_index + 1}/{len(self.char_sets)})...")
  159.  
  160. for length in range(current_length, max_length + 1):
  161. if length in self.current_state['completed_lengths']:
  162. continue
  163.  
  164. print(f" Length {length}: ", end="", flush=True)
  165.  
  166. # Calculate total combinations for progress
  167. total_combinations = len(char_set) ** length
  168. combinations_checked = 0
  169.  
  170. # Generate combinations starting from saved index
  171. for i, attempt in enumerate(itertools.product(char_set, repeat=length)):
  172. if i < current_index:
  173. continue
  174.  
  175. word = ''.join(attempt)
  176.  
  177. # Skip if already attempted
  178. if word in self.current_state['attempted_words']:
  179. continue
  180.  
  181. hash_value = self.sha256_hash(word)
  182. self.attempts += 1
  183. self.current_state['attempted_words'].add(word)
  184. self.log_attempt(word, hash_value)
  185.  
  186. # Update current state
  187. self.current_state['char_set_index'] = cs_index
  188. self.current_state['current_length'] = length
  189. self.current_state['current_index'] = i + 1
  190.  
  191. # Show progress
  192. combinations_checked += 1
  193. if combinations_checked % 10000 == 0:
  194. elapsed = time.time() - self.start_time
  195. rate = self.attempts / elapsed if elapsed > 0 else 0
  196. print(".", end="", flush=True)
  197.  
  198. # Auto-save every 10,000 attempts
  199. if combinations_checked % 100000 == 0:
  200. self.save_state()
  201.  
  202. # Check if found
  203. if hash_value == self.target_hash:
  204. self.found_word = word
  205. self.log_attempt(word, hash_value, found=True)
  206. return True
  207.  
  208. # Completed this length
  209. print(f" ({combinations_checked:,} combinations)")
  210. self.current_state['completed_lengths'].append(length)
  211. self.current_state['current_index'] = 0
  212. self.save_state()
  213.  
  214. # Completed this character set
  215. self.current_state['char_sets_tried'].append(cs_index)
  216. self.current_state['current_length'] = 1
  217. self.save_state()
  218.  
  219. return False
  220.  
  221. def display_stats(self):
  222. """Display current statistics"""
  223. if self.start_time:
  224. elapsed = time.time() - self.start_time
  225. rate = self.attempts / elapsed if elapsed > 0 else 0
  226. print(f"\nStatistics:")
  227. print(f" Total attempts: {self.attempts:,}")
  228. print(f" Time elapsed: {elapsed:.2f} seconds")
  229. print(f" Hash rate: {rate:,.0f} hashes/sec")
  230. print(f" State file: {self.state_file}")
  231. print(f" Log file: {self.log_file}")
  232.  
  233. def verify_result(self):
  234. """Verify the found word"""
  235. if self.found_word:
  236. actual_hash = self.sha256_hash(self.found_word)
  237. print("\n" + "=" * 60)
  238. print("VERIFICATION:")
  239. print(f"Word: '{self.found_word}'")
  240. print(f"Expected SHA256: {self.target_hash}")
  241. print(f"Actual SHA256: {actual_hash}")
  242. print(f"Match: {actual_hash == self.target_hash}")
  243. print("=" * 60)
  244. return actual_hash == self.target_hash
  245. return False
  246.  
  247. def cleanup(self):
  248. """Clean up state file if search is complete"""
  249. if self.found_word and os.path.exists(self.state_file):
  250. os.remove(self.state_file)
  251. print(f"State file {self.state_file} removed.")
  252.  
  253. def main():
  254. target_hash = "86f61bf1bc1fe799467b9a3220d7559941bd849c783395e554b101241cc2f46a"
  255.  
  256. print("SHA256 Hash Word Finder with Resume/Pause")
  257. print("=" * 60)
  258. print(f"Target: {target_hash}")
  259. print("Press Ctrl+C to pause and save progress")
  260. print("=" * 60)
  261.  
  262. # Initialize finder
  263. finder = HashFinder(target_hash)
  264.  
  265. try:
  266. # Try to load previous state
  267. state_loaded = finder.load_state()
  268.  
  269. if state_loaded and finder.found_word:
  270. print("Previous successful search found!")
  271. finder.verify_result()
  272. return
  273.  
  274. # Start search
  275. if not finder.found_word:
  276. if not state_loaded or not finder.try_common_words():
  277. print("\nStarting/Resuming brute force search...")
  278. found = finder.brute_force_with_resume(max_length=6)
  279.  
  280. if found:
  281. print(f"\n✓ SUCCESS! Found: '{finder.found_word}'")
  282. else:
  283. print(f"\n✗ Not found with current parameters.")
  284.  
  285. # Display final stats
  286. finder.display_stats()
  287.  
  288. # Verify result
  289. if finder.found_word:
  290. finder.verify_result()
  291. finder.cleanup()
  292.  
  293. except KeyboardInterrupt:
  294. print("\n\n⏸️ Search paused by user")
  295. finder.save_state()
  296. finder.display_stats()
  297. print("You can resume later by running the program again.")
  298. except Exception as e:
  299. print(f"\n❌ Error: {e}")
  300. finder.save_state()
  301. print("Progress saved. You can resume later.")
  302.  
  303. if __name__ == "__main__":
  304. main()
Success #stdin #stdout 0.02s 25476KB
stdin
Standard input is empty
stdout
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()