Skip to content

Tag: hash

Spring Security delegating password encoder

The Spring Security PasswordEncoder interface exists to make it easy to safely encode passwords for storage in a database. Hashing the password using a secure algorithm with a heavy work factor will slow down an attacker even if they compromise the password database.

Since the interface was introduced, security recommendations have changed as CPUs / GPUs become more powerful and as vulnerabilities are discovered in legacy algorithms. The original StandardPasswordEncoder is now deprecated as the SHA-256 algorithm is considered insecure. Spring offers more secure implementations based on bcrypt, PBKDF2 and Argon2.

However, Spring no longer ties you to a single algorithm. The new DelegatingPasswordEncoder provides support for multiple PasswordEncoder implementations, many of which are available in Spring Boot applications with default configuration. This makes it possible to select an algorithm at run time and to have a database containing password hashes with different algorithms.

Hashing and Salting passwords with Spring Security PasswordEncoder

A standard Spring Security configuration uses username / password based authentication. This always presents a tricky problem: how to securely store a user’s password in such a way that it can’t be read by anyone with access to our database. It’s naive to assume that our password database is 100% secure, just ask Adobe, Sony, Ashley Madison, and every other large organization that has had their database breached. Even if the database isn’t ‘breached’ or ‘leaked’, legitimate database admins or sys admins still have access to user passwords. A database containing user passwords is a liability that we’d rather not have.

The standard solution to this problem is store store a hash of the password rather than the plain text or even encrypted text. I don’t want to focus on why this is good or how it works as many others have done this already. I’ve found no better discussion of this (and password management in general) than Troy Hunt’s post on Everything you ever wanted to know about building a secure password reset feature.

Getting the details right when implementing password storage is critical. Some hash algorithms are vulnerable or just not suited to password hashing. If the salt is too short or predictable, it may be possible to retrieve the password from the hash. Any number of subtle bugs in coding could result in a password database that is vulnerable in one way or another. Fortunately, Spring Security includes password hashing out of the box. What’s more, since version 3.1, Spring Security automatically takes care of salting too.