Spring Security's `PasswordEncoder` interface is used to perform a one way transformation of a password to allow the password to be stored securely.
Given `PasswordEncoder` is a one way transformation, it is not intended when the password transformation needs to be two way (i.e. storing credentials used to authenticate to a database).
Typically `PasswordEncoder` is used for storing a password that needs to be compared to a user provided password at the time of authentication.
[[authentication-password-storage-history]]
== Password Storage History
Throughout the years the standard mechanism for storing passwords has evolved.
In the beginning passwords were stored in plain text.
The passwords were assumed to be safe because the data store the passwords were saved in required credentials to access it.
However, malicious users were able to find ways to get large "data dumps" of usernames and passwords using attacks like SQL Injection.
Developers were then encouraged to store passwords after running them through a one way hash such as SHA-256.
When a user tried to authenticate, the hashed password would be compared to the hash of the password that they typed.
This meant that the system only needed to store the one way hash of the password.
If a breach occurred, then only the one way hashes of the passwords were exposed.
Since the hashes were one way and it was computationally difficult to guess the passwords given the hash, it would not be worth the effort to figure out each password in the system.
To defeat this new system malicious users decided to create lookup tables known as https://en.wikipedia.org/wiki/Rainbow_table[Rainbow Tables].
Rather than doing the work of guessing each password every time, they computed the password once and stored it in a lookup table.
To mitigate the effectiveness of Rainbow Tables, developers were encouraged to use salted passwords.
Instead of using just the password as input to the hash function, random bytes (known as salt) would be generated for every users' password.
The salt and the user's password would be ran through the hash function which produced a unique hash.
The salt would be stored alongside the user's password in clear text.
Then when a user tried to authenticate, the hashed password would be compared to the hash of the stored salt and the password that they typed.
The unique salt meant that Rainbow Tables were no longer effective because the hash was different for every salt and password combination.
In modern times we realize that cryptographic hashes (like SHA-256) are no longer secure.
The reason is that with modern hardware we can perform billions of hash calculations a second.
This means that we can crack each password individually with ease.
Developers are now encouraged to leverage adaptive one-way functions to store a password.
Validation of passwords with adaptive one-way functions are intentionally resource (i.e. CPU, memory, etc) intensive.
An adaptive one-way function allows configuring a "work factor" which can grow as hardware gets better.
It is recommended that the "work factor" be tuned to take about 1 second to verify a password on your system.
This trade off is to make it difficult for attackers to crack the password, but not so costly it puts excessive burden on your own system.
Spring Security has attempted to provide a good starting point for the "work factor", but users are encouraged to customize the "work factor" for their own system since the performance will vary drastically from system to system.
Examples of adaptive one-way functions that should be used include <<authentication-password-storage-bcrypt,bcrypt>>, <<authentication-password-storage-pbkdf2,PBKDF2>>, <<authentication-password-storage-scrypt,scrypt>>, and <<authentication-password-storage-argon2,argon2>>.
Because adaptive one-way functions are intentionally resource intensive, validating a username and password for every request will degrade performance of an application significantly.
There is nothing Spring Security (or any other library) can do to speed up the validation of the password since security is gained by making the validation resource intensive.
Users are encouraged to exchange the long term credentials (i.e. username and password) for a short term credential (i.e. session, OAuth Token, etc).
The short term credential can be validated quickly without any loss in security.
[[authentication-password-storage-dpe]]
== DelegatingPasswordEncoder
Prior to Spring Security 5.0 the default `PasswordEncoder` was `NoOpPasswordEncoder` which required plain text passwords.
Based upon the <<authentication-password-storage-history,Password History>> section you might expect that the default `PasswordEncoder` is now something like `BCryptPasswordEncoder`.
Such that `id` is an identifier used to look up which `PasswordEncoder` should be used and `encodedPassword` is the original encoded password for the selected `PasswordEncoder`.
The `id` must be at the beginning of the password, start with `{` and end with `}`.
If the `id` cannot be found, the `id` will be null.
For example, the following might be a list of passwords encoded using different `id`.
All of the original passwords are "password".
.DelegatingPasswordEncoder Encoded Passwords Example
<1> The first password would have a `PasswordEncoder` id of `bcrypt` and encodedPassword of `$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG`.
When matching it would delegate to `BCryptPasswordEncoder`
<2> The second password would have a `PasswordEncoder` id of `noop` and encodedPassword of `password`.
When matching it would delegate to `NoOpPasswordEncoder`
<3> The third password would have a `PasswordEncoder` id of `pbkdf2` and encodedPassword of `5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc`.
When matching it would delegate to `Pbkdf2PasswordEncoder`
<4> The fourth password would have a `PasswordEncoder` id of `scrypt` and encodedPassword of `$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=`
When matching it would delegate to `SCryptPasswordEncoder`
<5> The final password would have a `PasswordEncoder` id of `sha256` and encodedPassword of `97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0`.
When matching it would delegate to `StandardPasswordEncoder`
[NOTE]
====
Some users might be concerned that the storage format is provided for a potential hacker.
This is not a concern because the storage of the password does not rely on the algorithm being a secret.
Additionally, most formats are easy for an attacker to figure out without the prefix.
For example, BCrypt passwords often start with `$2a$`.
====
[[authentication-password-storage-dpe-encoding]]
=== Password Encoding
The `idForEncode` passed into the constructor determines which `PasswordEncoder` will be used for encoding passwords.
In the `DelegatingPasswordEncoder` we constructed above, that means that the result of encoding `password` would be delegated to `BCryptPasswordEncoder` and be prefixed with `+{bcrypt}+`.
Our example in <<authentication-password-storage-dpe-format,Password Storage Format>> provides a working example of how this is done.
By default, the result of invoking `matches(CharSequence, String)` with a password and an `id` that is not mapped (including a null id) will result in an `IllegalArgumentException`.
This behavior can be customized using `DelegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(PasswordEncoder)`.
By using the `id` we can match on any password encoding, but encode passwords using the most modern password encoding.
This is important, because unlike encryption, password hashes are designed so that there is no simple way to recover the plaintext.
Since there is no way to recover the plaintext, it makes it difficult to migrate the passwords.
While it is simple for users to migrate `NoOpPasswordEncoder`, we chose to include it by default to make it simple for the getting started experience.
This does hash the password that is stored, but the passwords are still exposed in memory and in the compiled source code.
Therefore, it is still not considered secure for a production environment.
For production, you should <<authentication-password-storage-boot-cli,hash your passwords externally>>.
[[authentication-password-storage-boot-cli]]
=== Encode with Spring Boot CLI
The easiest way to properly encode your password is to use the https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-cli.html[Spring Boot CLI].
For example, the following will encode the password of `password` for use with <<authentication-password-storage-dpe>>:
If you are migrating from Spring Security 4.2.x you can revert to the previous behavior by <<authentication-password-storage-configuration,exposing a `NoOpPasswordEncoder` bean>>.
The default implementation of `BCryptPasswordEncoder` uses strength 10 as mentioned in the Javadoc of https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.html[BCryptPasswordEncoder]. You are encouraged to
tune and test the strength parameter on your own system so that it takes roughly 1 second to verify a password.
https://w3c.github.io/webappsec-change-password-url/[A Well-Known URL for Changing Passwords] indicates a mechanism by which password managers can discover the password update endpoint for a given application.
With the above configuration, when a password manager navigates to `/.well-known/change-password`, then Spring Security will redirect to `/update-password`.