How do I convert password hashing from MD5 to SHA?

Bruce Alderman picture Bruce Alderman · Sep 4, 2009 · Viewed 19k times · Source

I've got an old application that has user passwords stored in the database with an MD5 hash. I'd like to replace this with something in the SHA-2 family.

I've thought of two possible ways to accomplish this, but both seem rather clunky.

1) Add a boolean "flag" field. The first time the user authenticates after this, replace the MD5 password hash with the SHA password hash, and set the flag. I can then check the flag to see whether the password hash has been converted.

2) Add a second password field to store the SHA hash. The first time the user authenticates after this, hash the password with SHA and store it in the new field (probably delete their MD5 hash at the same time). Then I can check whether the SHA field has a value; this essentially becomes my flag.

In either case, the MD5 authentication would have to remain in place for some time for any users who log in infrequently. And any users who are no longer active will never be switched to SHA.

Is there a better way to do this?

Answer

Jørn Schou-Rode picture Jørn Schou-Rode · Sep 4, 2009

Essentially the same, but maybe more elegant than adding extra fields: In the default authentication framwork in Django, the password hashes are stored as strings constructed like this:

hashtype$salt$hash

Hashtype is either sha1 or md5, salt is a random string used to salt the raw password and at last comes the hash itself. Example value:

sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4