Sunday, February 28, 2010

Encoding A String With MD5

If you are to the point in your web app where you are ready to start dealing with user accounts and authentication, you may be thinking about cookies. Before you dive into any of this, please read chapter 14 of DjangoBook.com (all of it). It has tons of useful information about Django's built in account system that is already integrated with the Django Admin.

Now that we have that cleared up, lets get into some md5 encoding. Python offers a method pretty similar to PHP when it comes to md5. Simply include the hashlib library and you're good to go. Lets see how it would be done in PHP first.
$string = 'hello world';
$encoded_string = md5($string);
And here is the equivalent in Python.
import hashlib
string = 'hello world'
encoded_string = hashlib.md5(string).hexdigest()
Obviously, the import belongs at the top of your file, but you should know that. One key thing to keep in mind that hashlib is new in Python 2.5. In older versions, you would use md5.

Remember, simply using md5 does not mean a string will be secure. Don't forget to use a salt! If you don't know what that is, you can try reading something like this, or google it.

2 comments:

  1. If you don't know what a salt is, or even if you do, you probably shouldn't be implementing a user authentication feature. Just use someone else's well tested one.

    ReplyDelete
  2. You should also be wary of MD5 - use SHA1 which is available in PHP, and Python through hashlib.

    ReplyDelete