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).

Related posts:

  1. Using GitHub for a Grails Plugin (Revised)
  2. Developing Grails Plugins with GitHub
  3. The Kid Sister Crypto Manifesto
  4. “Grails Persistence with GORM and GSQL” has gone public
  5. OS-X Shortcuts for Grails (and Other Stuff)
This entry was posted in Groovy, Open Source. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • Rudie Ekkelenkamp

    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.

  • Categories