# There a many reasons to hash data. # For this example we'll say that we # want to has passwords so we can store # them in a database (or file)...or for # this example a variable # hashlib encapsulates the following functionality: # md5 # sha1 # sha224 # sha256 # sha384 # sha512 import hashlib # When a user creates their account they'll input # a password. For security purposes you hash # the password and store it (so they can log into # their account later). password = "$uperP@a$$w0rd" #pass the password to the sha1 constructor createSha1 = hashlib.sha1(password) #dump the password out in text sha1_password = createSha1.hexdigest() print sha1_password #output: # 2d0b537e6673e1f6baf1c462cd4922dab32ee243 # You'll notice that sha1 creates a 40 character hash. # All hashed strings (regardless of original size) will # be represented by sha1 as 40 characters. print len(sha1_password) #output: # 40 # You can store that hashed password and then later the # user will attempt to login. Take their password and hash # it with the same algorithm (sha1 in our example). password_attempt_1 = "superP@a$$w0rd" password_attempt_2 = "$up3rP@a$$w0rd" password_attempt_3 = "$uperP@a$$w0rd" #take the attempts and hash them so you can compare passwords attempt1 = hashlib.sha1(password_attempt_1) if sha1_password == attempt1.hexdigest(): print "password attempt 1 is a success" else: print "password attempt 1 is a failure" attempt2 = hashlib.sha1(password_attempt_2) if sha1_password == attempt2.hexdigest(): print "password attempt 2 is a success" else: print "password attempt 2 is a failure" attempt3 = hashlib.sha1(password_attempt_3) if sha1_password == attempt3.hexdigest(): print "password attempt 3 is a success" else: print "password attempt 3 is a failure" #output: # password attempt 1 is a failure # password attempt 2 is a failure # password attempt 3 is a success # Now that you understand how to use sha1 you # understand how to use all of the supported # algorithms in hashlib. They all use the same # methods so you can easily adapt your code to # any of the hash types. # Check out the python docs for hashlib
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Showing posts with label password. Show all posts
Showing posts with label password. Show all posts
Thursday, October 1, 2009
Python - hash with md5 and sha1 (and others!)
Subscribe to:
Posts (Atom)