Hashing a password before putting it into a database - password-encryption

I am working on a project where we are using a custom user table. This table contains a password field. At the moment we save the plain text password into the database. what I want to ask is how do I save a hash of the password to the table instead? I have read about the Rfc2898DeriveBytes class but I don't know how to use this and how to generate salts and what the entire process is from start to finish.
Can you tell me what approach I might take?
Will each row in the user table need a salt value and if so where do I get this from?

You're on the right track with PBKDF2 / Rfc2898DeriveBytes. If you just need it for hashing passwords, have a look at SimpleCrypto.Net, which is basically a thin wrapper around Rfc2898DeriveBytes.
With SimpleCrypto.Net, you hash a user's password like this:
private ICryptoService cryptoService = new PBKDF2();
private void SetNewPassword(User user, string newPassword)
{
//a new password hash is generated from a generated salt with the default settings
user.Password = cryptoService.Compute(newPassword);
//assigning the generated salt to the user
user.PasswordSalt = cryptoService.Salt;
}
To check if a user entered the right password, you compute the hash with the same salt and compare it with the one you stored in your database:
private bool ValidatePassword(User user, string password)
{
//hash the password with the saved salt for that user
string hashed = cryptoService.Compute(password, user.PasswordSalt);
//return true if both hashes are the same
return hashed == user.Password;
}
Another possibility for securely hashing passwords is bcrypt. There is an implementation called BCrypt.Net.

Storing the password in a plain-text field is not a good idea.
Please refer to : What is the best way to keep passwords configurable, without having them too easily available to the casual human reader?

Related

Cannot obtain user by using filter with username and password

I am using the following code
email = validated_data["login"]
password = validated_data["password"]
user_obj = User.objects.filter(Q(email__exact=email) & Q(password__exact=password))
I changed the password from admin however no user is returned. However if I remove the password check then I get a user object back.The object that I get back if I remove the Q(password__exact=password) condition has _password field as None. This code has been working fine for a while but today it is not returning back the object. Am I missing something here ? I verified that I am receiving the correct username and password from the client.I also tried accessing the admin with that username and password (The account has staff status) and I was able to log in. So the password is correct but for some reason I cant obtain that user by filtering. ? What might I be doing wrong ?
password isn't stored in plain text, but as a hash (and a little more). Get the user by username and check the password:
# assumes there can be only one
user = User.objects.get(email=email)
# this checks the plaintext password against the stored hash
correct = user.check_password(password)
BTW, you don't need Q objects for logical AND. filter(email__exact=email, password__exact=password) would suffice, even though it doesn't make much sense, in this case.
it is because Django doesn't stores password as the simple text they are hashed, you cant perform a password__exact on that it will return none every time unless you are getting the same hash password = validated_data["password"] here

django password hash different everytime

if I create a hash using django's django.contrib.auth.hashers.make_password of the same string I get different hash every time. I don't understand how is this legal because as far as I know, hash functions must generate the same hash every time since by definition its a function. What am I missing?
from django.contrib.auth.hashers import make_password
password = "helloworld"
h1 = make_password(password)
h2 = make_password(password)
print h1, h2
h1 = u'pbkdf2_sha256$20000$Tr6NV5MewXYl$X+sezT6WRqBwYmJR/RZmZHLP6/l6ntSaBke0RKU1/v0='
h2 = u'pbkdf2_sha256$20000$05rEmxChtXlI$NdZGfTKH+kqt1viuFng3GmvBp6eJcsstxV4JcDlBGIs='
I suspect that different algorithms are used to hash every time and hence the hash is also different. Am I correct?
You see different results because of the salt. In simple words Django add some random string to the password before hashing to get different values even for same password. This makes rainbaw tables attack are useless. Actually what you see in DB is not plain hash value, it's structure in following format: <algorithm>$<iterations>$<salt>$<hash>
Each time you use make_password, the password is hashed with a different salt. Django stores the salt with the hashed password. You can then use check_password to check the password later.
from django.contrib.auth.hashers import check_password, make_password
password = "helloworld"
h1 = make_password(password)
check_password(password, h1) # returns True
check_password("incorrect", h1) # returns False
Read the docs on how Django stores passwords for more info.

How to generate hash in django 1.9 like Invitation Link

I want to send the email to the user that will contains url+hash
like this bleow
www.mywebsite.com/user/verify/121#$%3h2%^1kj3#$h2kj1h%$3kj%$21h
and save this hash against the user in the Database like this
ID | Email |Hash
1 | youremail#gmail.com |121#$%3h2%^1kj3#$h2kj1h%$3kj%$21h
When the user received the email it should check and compare the hash with it and perform the action as per situation.
My question is simple how to generate a unique hash for each user and how to store them in the Database.
If by "hash", you mean a unique string, you can just use uuid.uuid4 for that purpose.
>>> import uuid
>>> unique_id = str(uuid.uuid4())
>>> print unique_id
d8814205-f11e-46e1-925e-a878fc75cb8d
>>> # replace dashes, if you like
>>> unique_id.replace("-", "")
I've used this for projects where I need to verify a user's email.
P.S.: It's not called a hash, it's called a unique ID. Hashing is something else, where you generate a value from a given string. See this question for more explanation.
Django has a Cryptographic Signing module, which helps produce unique and verifiable signatures for any data you need. If you are trying to do this to verify that the request is done by the appropriate user or not, you can use the library to verify requests, without storing the hash in the database.

Understanding User class in django

I create a user in my view.py using this simple code.
if not errors:
user = User.objects.create_user(username, email, password)
user.save()
Except for the validation, there is nothing that I do to the username and password values before creating the object.
But I find this in the User class in Django API. I don't know how to use the help text. If it is help text what does it print? How do I find the default values of algo, salt and hexdigest?
password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the change password form."))
"If it is help text what does it print?"
-> it prints exactly this: Use '[algo]$[salt]$[hexdigest]'
when you create a user, it will automatically call make_password(password[, salt, hashers])
which: Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text. Optionally, you can provide a salt and a hashing algorithm to use, if you don't want to use the defaults (first entry of PASSWORD_HASHERS setting). Currently supported algorithms are: 'pbkdf2_sha256', 'pbkdf2_sha1', 'bcrypt' (see Using bcrypt with Django), 'sha1', 'md5', 'unsalted_md5'
are you facing any problems with this?
create_user will automatically generate password hash and it will create user in the database (thus you don't need that user.save())
See docs on creating users.
The help text is basicly just code for the message that shows up in the django admin, when editing a User object. It's meant to explain to someone looking at the edit form, why the password field has something like sha1$12345$1234567890abcdef1234567890abcdef12345678 instead of the password that was set for that user. The reason is, of course that the password is hashed for security, and that representation holds all the information required to verify a user-typed password later.
The admin user edit form has a special page for editing passwords. If you want to edit the users password in your code use the set_password method of the User object, the check_password method is for verifying a supplied password.
The documentation for make_password has more information about the algorithms Django uses and can use. The default for Django <1.3 was sha1, Django 1.4 changed the default to PBKDF2. The default value for salt is a random string (it's there so that two identical passwords don't look the same in the database). Hexdigest is the value of the password string and the salt string hashed with the hashing algorithm. You can read the details in the code on github.

Using Fluent NHibernate Persistence Tester Tool with Object that has encrypted Password field

First of all: I am completely new to Fluent and NHibernate.
I have a User object that contains a password field. When setting that field the value gets encrypted. Now I try to use the
new PersistenceSpecification<User>(session)
...
.CheckProperty(p => p.Password, "secret")
...
.VerifyTheMappings();
persistence checker tool. The problem I am facing is the handling of the password field. The debugger told me that the tool calls the Password field setter multiple times. The first time with the cleartext password "secret". The following times with the encrypted versions ending up with encrypting my password multiple times.
Any idea how to cope with this?
EDIT:
NHibernate has to set the password on the user after it loaded it from db and when you use the standard
Map(user => user.Password);
it will use the property to set the db-value
Map(user => user.Password).Access.CamelCaseField(Prefix.Underscore);
prevents this then
A way to solve this is to use a setter method to set your password, for example
public virtual void UpdatePassword(string newPassword)
{
string hashedPassword = HashPassword(newPassword);
_password = hashedPassword;
}
This way your hash/encryption logic is separate from your property setter. In your PersistenceSpecification test you will then be testing the saving/getting of the encrypted text.
If you need to decrypt the password use a getter method to get the decrypted password (the Password property will contain the encrypted text).
public virtual string GetPasswordDecrypted()
{
...
}
As a side note, unless you have a good reason it will be better to hash the password than encrypt it.