Viktn0r
Viktn0r

Reputation: 1

Can't get the hash() function to work in python 3.2.2

I have a problem with this code:

print('insert password below to get a hash')
pass = int(input('Input passowrd> ')

hash(pass)
input()

I just get a error when I try to run this, I tried the help(hash) in the python shell, read the docs, googled as much as possible, but I can't get it to work :-/

What is the problem?

Upvotes: 0

Views: 258

Answers (4)

yak
yak

Reputation: 9041

pass is a statement, you can't have a variable with that name in Python.

>>> pass = 1
SyntaxError: invalid syntax
>>> 

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838974

I think you have two problems.


Firstly, a pass-word is not usually an integer so your call to int will most likely raise an exception.

You probably want this:

pass = input('Input password> ')

Secondly, the hash function returns a hash code for the object for fast comparison purposes. It is not a cryptographic hash function. Consider using something like the commonly used MD5 algorithm or (preferably) something more secure like the SHA-2 family of algorithms instead.

You can use hashlib to generate hashes that are cryptographically secure. Example:

>>> import hashlib    
>>> hashlib.md5('admin'.encode('utf-8')).hexdigest()
'21232f297a57a5a743894a0e4a801fc3'
>>> hashlib.sha256('admin'.encode('utf-8')).hexdigest()
'8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918'

Depending on your needs, you may also want to consider using a salt to further protect the password.

Upvotes: 3

Raymond Hettinger
Raymond Hettinger

Reputation: 226634

Your code works are written, but it probably isn't what you expected (the hash of an integer is just the integer itself). Try this instead:

print('insert password below to get a hash')
pass_str = input('Input password: ')
h = hash(pass_str)

Also, if you're storing hash values for passwords and want it to be secure, be sure to use a cryptographically strong hash such as those found in the hashlib module:

>>> pass_str = 'the phrase that pays'
>>> hashlib.sha256(pass_str.encode()).hexdigest()
'a91ba2a03eb9772b114e6db5c5a114d8a9b3ba419a64cdde9606a9151c8a352e'

Upvotes: 3

Thomas
Thomas

Reputation: 182038

In the future, it would help to post the error you're getting. I bet it's a ValueError that complains that the password cannot be converted to an int, which is quite correct.

There is no point in converting to an integer in the first place; hash works just fine for strings:

print('Input password below to get a hash:')
pass = input('Input password> ')
print(hash(pass))
input()

Upvotes: 0

Related Questions