如何使用ShaPasswordEncoder正确编码密码?

mis*_*sco 5 java hash spring sha spring-security

我想ShaPasswordEncoder在我的Spring应用程序中使用密码编码.

ShaPasswordEncoder sha = new ShaPasswordEncoder(256);
sha.setIterations(1000);
String hash = sha.encodePassword(password, salt);
Run Code Online (Sandbox Code Playgroud)

但我不应该把它放在那里salt param.它可以是静态短语(例如sT4t1cPhr453),还是每个用户不同的动态字符串(例如用户名或用户ID)?

编辑:

我用户自定义AuthenticationProvider,所以我的安全上下文如下:

<authentication-manager>
   <authentication-provider ref="customAuthenticationProvider" />
</authentication-manager>

<beans:bean id="customAuthenticationProvider" class="com.app.cloud.auth.CustomAuthenticationProvider">

@Component("customAuthenticationProvider")
public class CustomAuthenticationProvider implements org.springframework.security.authentication.AuthenticationProvider {

    @Autowired
    private AuthService authService;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException,BadCredentialsException {
    //...
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*mar 12

如果您想明确定义salt,可以定义salt源:

动态盐(基于用户名属性)

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="userDetailsService">
        <password-encoder hash="sha-256">
            <salt-source user-property="username"/>
        </password-encoder>
    </authentication-provider>
</authentication-manager>
Run Code Online (Sandbox Code Playgroud)

静盐

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="userDetailsService">
        <password-encoder hash="sha-256">
            <salt-source system-wide="MySalt" />
        </password-encoder>
    </authentication-provider>
</authentication-manager>
Run Code Online (Sandbox Code Playgroud)

推荐的方法

如果您使用的是Spring Security 3.1,建议的方法是使用bcrypt,这会自动生成一个盐并连接它.

<beans:bean id='bCryptPasswordEncoder' class='org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder'/>

<authentication-manager>
  <authentication-provider user-service-ref="userDetailsService">
          <password-encoder ref="bCryptPasswordEncoder"/>
  </authentication-provider>
</authentication-manager>
Run Code Online (Sandbox Code Playgroud)

您可以像这样生成用户密码:

String password = "p4ssword";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(password);
Run Code Online (Sandbox Code Playgroud)