Salted and Hashed Passwords in Grails via the Crypto Plugin

I wanted to share this tidbit n how to do salted and hashed passwords in Grails. If you don’t know why you want to do this, read Never store passwords in a database!. More on salting is available at Wikipedia’s article on Password Cracking.

To be smarter about passwords than the Reddit developers, first install the Crypto plugin via: grails install-plugin crypto. More information on the Crypto plugin is available on the Grails website: Grails Crypto Plugin Documentation.

I tend to then structure the password part of my application user class to look something like this:

import static cr.co.arquetipos.password.PasswordTools.*
 
class AppUser {
 
  static transients = ['password']
 
  String passwordHash
 
  boolean checkPassword(String password) {
    checkDigestBase64(password, passwordHash)
  }
 
  void setPassword(String password) {
    passwordHash = saltPasswordBase64(password)
  }
 
}

Once that’s done, you can execute code like this:

def user = new AppUser()
user.password = "foo"
assertTrue user.checkPassword("foo")

Note that this won’t work:

   assertEquals "foo", user.password // Fails because the 'password' property can't be found

Using this approach, the password is not stored in the database, or even in a transient property in the domain object. This minimizes the tendency to do something stupid (like e-mail the password in cleartext).

This entry was posted in Groovy, Open Source. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Rudie Ekkelenkamp
    Posted June 29, 2009 at 2:02 AM | Permalink

    Thanks for the post. Actually the example code isn’t working with the crypto 2.0 release. The checkDigestBase64(password) needs the hashed password as parameter as well.

    checkDigestBase64(password, passwordHash)

    cheers,

    Rudie.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">