[PYTHON] Hash with the standard library hashlib and compare login passwords

It seems that there is a library that can easily hash in the Python standard library, so I tried using it

test1.py


# -*- coding: utf-8 -*-

import hashlib

if __name__ == "__main__":

	#Creating a hash object
	md5 = hashlib.md5()

	#Set of strings
	md5.update("password")

	print md5.digest()
	print md5.hexdigest()

test1.Output result of py


_M;Ze ヨ ・ Gukpa
5f4dcc3b5aa765d61d8327deb882cf99

ʻImport import by writing hashlib`.

  1. Create an object according to the algorithm you want to use (this time use md5)
  2. Set the character string you want to hash in the created object
  3. Hash with .hexdigest (I'm not sure about .digest)

It seems that the original character string cannot be known once it is hashed. So your password will never be known to anyone! !!

Check if the original password matches the password entered

You can also hash the entered password and compare it.

hash_test.py


# -*- coding: utf-8 -*-

import hashlib
import sys

def createHash(password):

	#Creating a hash object
	hashObj = hashlib.md5()

	#Specify the character string to be hashed
	hashObj.update(password)

	#Returns the hashed version
	return hashObj.hexdigest()


if __name__ == "__main__":

	#Hash the original password
	checkPass = createHash("password")

	#Get command line arguments
	password = sys.argv[1]

	#Hashing
	password = createHash(password)

	#Does the entered password match?
	if checkPass == password:
		print u"Login successful"
	else:
		print u"Login failure"

hash_test.Execution result of py


\python>hash_test.py pass
Login failure

\python>hash_test.py password
Login successful

\python>hash_test.py Password
Login failure

It seems that it is also case sensitive (naturally ...)

References

Documentation [About hashing](http://e-words.jp/w/%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E9%96%A2% E6% 95% B0.html, "What is a hash function? | Message digest function | Hash algorithm --Meaning / Definition: IT Glossary")

Recommended Posts

Hash with the standard library hashlib and compare login passwords
What you can do with the Python standard library statistics
I compared the speed of Hash with Topaz, Ruby and Python
Compare DCGAN and pix2pix with keras
Login with PycURL and receive response
Compare two images with image hash
Compare nighttime and daytime returns on the Nikkei Stock Average with python
Dispersion with Python's standard library and Pillow Find the RGB standard deviation of the image and determine if it is monochromatic
Calculate and display standard weight with python
2. Mean and standard deviation with neural network!
How to pass the path to the library built with pyenv and virtualenv in PyCharm
Solving the traveling salesman problem with the genetic algorithm (GA) and its library (vcopt)