Generating Secure Hashes in Python

Discussion in 'Python' started by pradeep, Aug 11, 2012.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    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.

    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 ='ripemd160');
    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"
        print "Does not match"
    ## if we want to add lots of data and then get the digest in the end
    md5 = hashlib.md5()
    ## add data as much as you want
    print md5.hexdigest()


Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice