Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Generating Secure Hashes in Python (http://www.go4expert.com/articles/generating-secure-hashes-python-t28864/)

pradeep 11Aug2012 14:24

Generating Secure Hashes in Python
 
Secure hashes, message digests, or simply digest as they are popularly known are specific algorithms which take data of any type and any size and return a fixed bit length data that'll always be the same for the arbitrary data provided, in case the data is modified the hash will change vastly.

Secure hashes are used to verify message integrity, in cryptography, as many similar uses. You might have noticed that when you download some software or CD/DVD images (mainly open source) they also provide the md5sum with it, which can be used to verify the integrity of the downloaded file, if the MD5 digest of the downloaded file matches that of the original file it means that the downloaded file is same as the original file and the downloaded file is not corrupt.

There are a number of hashing algorithms, like MD4, MD5, SHA-1, SHA-2, etc. Some have been deprecated by it's successors, others may have weaknesses, as of now SHA-512 and RIPEMD-320 are the best hashing algorithms.

Genrating Secure Hashes



We'll be using the hashlib module provided by Python for generating all available secure hashes, all popular ones are available in the module. Follow the demo code below, to get an overview of the module & various algorithms' usage.

Code: Python

#!/usr/bin/python26

import hashlib

## let's print the hex-digest with a few popular algorithms
## hex-digest so that we can print/store them, else the output would be binary
print 'MD5: ',hashlib.md5("pradeep").hexdigest()
print 'SHA-1: ',hashlib.sha1("go4expert").hexdigest()
print 'SHA-224: ',hashlib.sha224("Asha").hexdigest()
print 'SHA-256: ',hashlib.sha256("Anjali").hexdigest()

## some algorithms dont have methods by their names, so you'll need to create an object
ripmed = hashlib.new('ripemd160');
ripmed.update('Shabbir')
print 'RIPEMD-160: ',ripmed.hexdigest()

## let's now try matching a string and it's uppercase version to check their digest
if hashlib.md5("pradeep").hexdigest() == hashlib.md5("PRADEEP").hexdigest():
    print "Matches"
else:
    print "Does not match"

## if we want to add lots of data and then get the digest in the end
md5 = hashlib.md5()
md5.update("FirstLine")
## add data as much as you want
md5.update("SecondLine")
print md5.hexdigest()


References



http://en.wikipedia.org/wiki/Cryptog...ash_algorithms


All times are GMT +5.5. The time now is 18:00.