Dictionary Attack in Python

Got an MD5 or SHA1 password hash and a password dictionary? Want to crack the hashed password but don't want to use tools like Cain or Hydra? Here's how to write a hash cracker in python from scratch:

#! /usr/bin/env python
# HashCrack.py
# Author: Abdul Fatir
# E-Mail: abdulfatirs@gmail.com

import hashlib
import optparse

def crackMD5Hash(_file,_hash):
 _wordlistfile = open(_file,"r")
 cracked = False
 for word in _wordlistfile:
  _purgedword = word.strip()
  md5 = hashlib.md5()
  md5.update(_purgedword)
  _wordhash = md5.hexdigest()
  if _wordhash == _hash:
   
   print "[ ] Hash (" _hash  ") cracked: " _purgedword
   cracked = True
   break
 if(not cracked):
  print "[-] Unable to crack the hash."
  
def crackSHA1Hash(_file,_hash):
 _wordlistfile = open(_file,"r")
 cracked = False
 for word in _wordlistfile:
  _purgedword = word.strip()
  sha1 = hashlib.sha1()
  sha1.update(_purgedword)
  _wordhash = sha1.hexdigest()
  if _wordhash == _hash:
   print "[ ] Hash (" _hash  ") cracked: " _purgedword
   cracked = True
   break
 if(not cracked):
  print "[-] Unable to crack the hash."

def Main():
 argparser = optparse.OptionParser("usage %prog -f <wordlist file> -p <hash to be cracked> -a <hash algorithm>")
 argparser.add_option('-f', dest='filename',type='string',help='Please specify a word list')
 argparser.add_option('-p', dest='passhash',type='string',help='Please specify a password hash to be cracked')
 argparser.add_option('-a', dest='hashalgo',type='string',help='Please specify a hash algorithm')
 (options, arg) = argparser.parse_args()
 if (options.filename == None) | (options.passhash == None) | (options.hashalgo == None):
  print argparser.usage
  exit(0)
 else:
  filename = options.filename
  passhash = options.passhash
  hashalgo = options.hashalgo
 print "[*] Cracking hash ..."
 if (hashalgo == 'MD5')|(hashalgo == 'md5'):
  crackMD5Hash(filename,passhash)
 elif (hashalgo == 'SHA1')|(hashalgo == 'sha1'):
  crackSHA1Hash(filename,passhash)
 
if __name__ == '__main__':
 Main()

Download this code from pastebin.

Notes:

  1. This is a mere prototype of how to perform a manual dictionary attack. This can be improved to much extent and more hashing algorithms can be added to it. Also consider using separate threads for searching password than the main thread in case of large dictionaries.
  2. This code requires Python 2.7.x.

Suggested Further Readings:

  1. Read more about python's hashlib and threading modules to improve this code.
  2. Read more on cryptographic hashing and other hashing algorithms. Refer to http://learncryptography.com for basic knowledge about cryptography.