0

Suppose I wish to store passwords in my code. Is SHA256 a good enough way to store them?

Here's what the code looks like:

#!/usr/bin/python3
#The password is 'helloWorld'

import hashlib

hashedString = "11d4ddc357e0822968dbfd226b6e1c2aac018d076a54da4f65e1dc8180684ac3"

for i in range(3):
  x = input('Password: ') # For now, ignore the fact that it's exposed.
  if hashlib.sha256(x.encode()).hexdigest() == hashedString:
    print('Access granted!')
    exit()
  else:
    print('Wrong password.')
print('3 attempts!')

Now, there are problems with this, such as the possibility that there are other strings with the same SHA256 hash.
So is there another way to store them (without giving explicit information such as password length, etc.)?

The Holy See
  • 193
  • 1
  • 1
  • 4

2 Answers2

1

I would recommend PBKDF2 if its available. Check this link out and see if it provides what you need.

The difference is that:
- PBKDF2 by design is slow
- SHA256 is a good hash function; it is not slow, by design

Password hashing algorithms such as PBKDF2, bcrypt, and scrypt are meant for use with passwords and are purposefully slow. Cryptographic hashing algorithms are fast. Fast is good in most situations, but not here. Slowing down the algorithm (usually by iteration) make the attacker's job much harder. Password hashes also add a salt value to each hash to make it unique so that an attacker can not attack multiple hashes at the same time.

See this post for more info on why to pick PBKDF2.

EDIT: PBKDF2 also provides padding, so you wont give out any information about password length.

Community
  • 1
  • 1
LuqJensen
  • 310
  • 6
  • 14
1

Actually there are two different questions contained in your question.

1) Is it safe enough to store the password with SHA-256?

No, normally this is not safe enough, a SHA-* hash can be calculated very fast, so you can brute-force with 14 Giga SHA-256 per second. If your password is very strong, a single iteration of SAH-256 can be safe enough. As soon as others can determine the password, or if humans should be able to remember it, you absolutely should switch to BCrypt, PBKDF2 or SCrypt.

2) Are collisions a problem?

No, it is extremely unlikely that you find another password producing the same hash, in practise this can be ignored. There is another good answer about the likeliness of such a collision.

Community
  • 1
  • 1
martinstoeckli
  • 23,430
  • 6
  • 56
  • 87