<commit_before>#!/usr/bin/env python
import hashlib
import re
from urllib import FancyURLopener
import sys
from optparse import OptionParser

HASH_REGEX = re.compile("([a-fA-F0-9]{32})")


class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'


def dictionary_attack(h, wordlist):
    for word in wordlist:
        if hashlib.md5(word).hexdigest() == h:
            return word

    return None


def format_it(hash, plaintext):
    return "{hash}:{plaintext}".format(hash=hash, plaintext=plaintext)


def crack_single_hash(h):
    myopener = MyOpener()
    response = myopener.open(
        "http://www.google.com/search?q={hash}".format(hash=h))

    wordlist = response.read().replace('.', ' ').replace(
        ':', ' ').replace('?', '').split(' ')
    plaintext = dictionary_attack(h, set(wordlist))

    return plaintext


class BozoCrack(object):

    def __init__(self, filename, *args, **kwargs):
        self.hashes = []

        with open(filename, 'r') as f:
            hashes = [h.lower() for line in f if HASH_REGEX.match(line)
                      for h in HASH_REGEX.findall(line.replace('\n', ''))]

        self.hashes = sorted(set(hashes))

        print "Loaded {count} unique hashes".format(count=len(self.hashes))

        self.cache = self.load_cache()

    def crack(self):
        for h in self.hashes:
            if h in self.cache:
                print format_it(h, self.cache[h])
                continue

            plaintext = crack_single_hash(h)

            if plaintext:
                print format_it(h, plaintext)
                self.cache[h] = plaintext
                self.append_to_cache(h, plaintext)

    def load_cache(self, filename='cache'):
        cache = {}
        with open(filename, 'r') as c:
            for line in c:
                hash, plaintext = line.replace('\n', '').split(':', 1)
                cache[hash] = plaintext
        return cache

    def append_to_cache(self, h, plaintext, filename='cache'):
        with open(filename, 'a') as c:
            c.write(format_it(hash=h, plaintext=plaintext))

if __name__ == '__main__':

    parser = OptionParser()
    parser.add_option('-s', '--single', metavar='MD5HASH',
                      help='cracks a single hash', dest='single', default=False)<commit_msg>Fix regression if cache file doesn't exist<commit_after>#!/usr/bin/env python
import hashlib
import re
from urllib import FancyURLopener
import sys
from optparse import OptionParser

HASH_REGEX = re.compile("([a-fA-F0-9]{32})")


class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'


def dictionary_attack(h, wordlist):
    for word in wordlist:
        if hashlib.md5(word).hexdigest() == h:
            return word

    return None


def format_it(hash, plaintext):
    return "{hash}:{plaintext}".format(hash=hash, plaintext=plaintext)


def crack_single_hash(h):
    myopener = MyOpener()
    response = myopener.open(
        "http://www.google.com/search?q={hash}".format(hash=h))

    wordlist = response.read().replace('.', ' ').replace(
        ':', ' ').replace('?', '').split(' ')
    plaintext = dictionary_attack(h, set(wordlist))

    return plaintext


class BozoCrack(object):

    def __init__(self, filename, *args, **kwargs):
        self.hashes = []

        with open(filename, 'r') as f:
            hashes = [h.lower() for line in f if HASH_REGEX.match(line)
                      for h in HASH_REGEX.findall(line.replace('\n', ''))]

        self.hashes = sorted(set(hashes))

        print "Loaded {count} unique hashes".format(count=len(self.hashes))

        self.cache = self.load_cache()

    def crack(self):
        for h in self.hashes:
            if h in self.cache:
                print format_it(h, self.cache[h])
                continue

            plaintext = crack_single_hash(h)

            if plaintext:
                print format_it(h, plaintext)
                self.cache[h] = plaintext
                self.append_to_cache(h, plaintext)

    def load_cache(self, filename='cache'):
        cache = {}
        with open(filename, 'a+') as c:
            for line in c:
                hash, plaintext = line.replace('\n', '').split(':', 1)
                cache[hash] = plaintext
        return cache

    def append_to_cache(self, h, plaintext, filename='cache'):
        with open(filename, 'a') as c:
            c.write(format_it(hash=h, plaintext=plaintext))

if __name__ == '__main__':

    parser = OptionParser()
    parser.add_option('-s', '--single', metavar='MD5HASH',
                      help='cracks a single hash', dest='single', default=False)
{'fraction_non_alphanumeric': 0.14027719445611087, 'fraction_numerical': 0.012179756404871903, 'mean_word_length': 2.448950036205648, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 4, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4644527', 'n_tokens_mistral': 1609, 'n_tokens_neox': 1519, 'n_words': 355}