使用Spring Security,Spring Boot和MongoDB进行密码编码和解码 [英] Password encoding and decoding using Spring Security, Spring Boot and MongoDB
问题描述
我使用上面提到的软件堆栈,并且需要先加密密码,然后再保存到数据库中.我还需要解密密码,因为当有人更改密码时,他需要输入旧密码,然后输入两次新密码,我需要检查旧密码. 我进行了很多搜索,但我仍然不确定执行此操作的正确方法是什么. 我已经找到此链接加密,但是还有其他提示做这个? 我也不确定MongoDB是否提供保护密码的功能.
I use the mentions software stack above and I need to encrypt password before save into database. I also need to decrypt password because when someone will change password he she needs to give in the old password and then the new onw twice and I need to check the old password. I have searched a lot but I still not sure what is the right way to do this. I have found this link Encrypting but are there other hints to do this? I also not sure if maybe MongoDB provides something to protect passwords.
推荐答案
首先阅读史蒂文·卡尔森的答案关于密码哈希.
First read Steven Carlson´s answer about password hashing.
好消息是Spring Security将为您完成此任务. Spring Security 3.2引入了新的 org.springframework.security.crypto.password.PasswordEncoder
接口和一些实现: StandardPasswordEncoder
(和NoOpPasswordEncoder
).
The good thing is that Spring Security will do this for you. Spring Security 3.2 introduced the new org.springframework.security.crypto.password.PasswordEncoder
interface and some implementations: BCryptPasswordEncoder
, StandardPasswordEncoder
(and NoOpPasswordEncoder
).
重要提示:请勿将org.springframework.security.
crypto.password
.PasswordEncoder
与旧的已弃用的org.springframework.security.
authentication.encoding
.PasswordEncoder
Important: Do not confuse org.springframework.security.
crypto.password
.PasswordEncoder
with the old deprecated org.springframework.security.
authentication.encoding
.PasswordEncoder
接口(以及实现)具有您需要的两种方法:
The interface (and therefore the implementations) has the two methods you need:
-
public String encode(CharSequence rawPassword)
-
public boolean matches(CharSequence rawPassword, String encodedPassword)
public String encode(CharSequence rawPassword)
public boolean matches(CharSequence rawPassword, String encodedPassword)
I recommend to use org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
.
The BCryptPasswordEncoder
(in contrast to the StandardPasswordEncoder
) use an salt that is different for each password (but not global like the one from StandardPasswordEncoder
). When you encode a raw password (public String encode(CharSequence rawPassword)
) then the returned encoded password is not just the encoded password, it also contains some meta information about the used hash-algorithm, the used salt and of course the encoded password.
这篇关于使用Spring Security,Spring Boot和MongoDB进行密码编码和解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!