We know that passwords are not encrypted. They are hashed using some cryptographically strong hash functions. (Why don’t we encrypt passwords in a database?) But, if we simply hash a password using a hash function, it will be cryptographically insecure. An attacker can easily use a rainbow table to derive the password. So, we need to use salts with passwords. (Why should we always store salts with hashed values of passwords?)
A salt is a string that is concatenated with the password string and the concatenated string is then hashed using a secure hash function. But, if we use the hash function only once, that also would be cryptographically less secure. So, we need to concatenate the salt string with the password string and the resulting concatenated string should be hashed using some secure hash function multiple times. Usually, we use a strong hash function like SHA-512 and we use the hash function thousands of times. For example, in Linux, we use the SHA-512 hash function 5000 times by default.
So, how should we generate a password hash in Python? In Python, we can use the module passlib to generate a password hash securely.
from passlib.hash import sha512_crypt password_hash = sha512_crypt.using(salt="o.ateVLe", rounds=5000).hash("abc123") print(password_hash)
Here, we are using the sha512_crypt() method. The string value “o.ateVLe” is used as salt. And, we are using the SHA-512 hash function 5000 times. The password string that is being hashed is “abc123”
By default, Linux uses the SHA-512 hash function 5000 times to hash a password. So, if we generate a password using this method and compare the generated password hash with the password hash in the /etc/shadow file, the resulting password hashes will be the same.
0 Comments