JDelage
JDelage

Reputation: 13662

How should I store my sha512 salted & hashed passwords in MySQL?

All,

I am using the following PHP function to salt & hash user passwords for a web app:

function stringHashing($password,$salt){
 $hashedString=$password.$salt;
 for ($i=0; $i<50; $i++){
  $hashedString=hash('sha512',$password.$hashedString.$salt);
  }
 return $hashedString;
}  

What is the best way to store the resulting string in MySQL? I suppose it is a fixed CHAR field? How should I go about calculating the right length?

Thanks,

JDelage

Upvotes: 15

Views: 20026

Answers (3)

Alastair
Alastair

Reputation: 6975

If someone knows your salt, they probably have your source code which guides them to repeat it 50 times. In that light, given the trivial security benefit to recursive re-hashing with a fixed-count, I thought I'd suggest using SHA2() from MySQL 5.5.5+ as a neater alternative:

mysql_query("SELECT SHA2(CONCAT('$password','$salt'), 512) AS `hash`;");

Which will be your VARCHAR(128) ready to INSERT/UPDATE.

Upvotes: 1

SamT
SamT

Reputation: 10610

I have always used a varchar field with a more-than-needed length. What if, down the road, you want to change your algorithm? You have to alter the table, which is annoying.

SHA512 will produce a 128 char string, so give the field at least that.

Also, I must point out that you are doing a lot of wasted processing. You are not adding too much security by iterating through the same salt and hash over and over and over again. Ultimately, you will still need a salt and password, everything else about the algorithm remains constant.

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346240

Well, SHA512 will always return a 512 bit hash, the two-argument hash() method returns this as hex digits, so that's 512 bits / 8 bits per byte * 2 hex digits per byte = 128 hex digits

A CHAR(128) should be what you need

Upvotes: 27

Related Questions