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