Home > python > md5 hash of a text / file + crack an md5 hash

md5 hash of a text / file + crack an md5 hash

Update (20140406)
The implementation of the function file_to_md5() was replaced. It still produces the same output.

(1) text / file => md5 (encode)
You have a text or a file and you want to generate its md5 hash.

#!/usr/bin/env python

import hashlib

def string_to_md5(content):
    """Calculate the md5 hash of a string.

    This 'string' can be the binary content of a file too."""
    md5 = hashlib.md5()
    md5.update(content)
    return md5.hexdigest()

def file_to_md5(filename, block_size=8192):
    """Calculate the md5 hash of a file. Memory-friendly solution,
    it reads the file piece by piece.

https://stackoverflow.com/questions/1131220/get-md5-hash-of-big-files-in-python"""

    md5 = hashlib.md5()
    with open(filename, 'rb') as f:
        while True:
            data = f.read(block_size)
            if not data:
                break
            md5.update(data)
    return md5.hexdigest()

#############################################################################

if __name__ == "__main__":
    text = 'uncrackable12'  # :)
    print string_to_md5(text)
    #
    filename = '/usr/bin/bash'
    print file_to_md5(filename)

The md5.hexdigest() returns a string of hex characters that is always 32 characters long. Thus, if you want to store it in a database, you can use the type CHAR(32).

(2) md5 => string (decode)
An md5 hash cannot be decoded, it’s a one-way process. However, you can try to find the md5 hash in a database that contains “string : md5″ pairs. One such online database is available at http://www.md5decrypter.co.uk/ for instance. See also dictionary attack.

About these ads
Categories: python Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.
Follow

Get every new post delivered to your Inbox.

Join 61 other followers

%d bloggers like this: