5

我想ShaPasswordEncoder在我的Spring应用程序中使用对密码进行编码。

ShaPasswordEncoder sha = new ShaPasswordEncoder(256);
sha.setIterations(1000);
String hash = sha.encodePassword(password, salt);

但我不应该投入什么salt param。它可以是静态短语(例如sT4t1cPhr453),还是每个用户都不同的动态字符串(例如用户名或用户 ID)?

编辑:

我使用 custom 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);
    }
}
4

2 回答 2

12

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

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

<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>

静态盐

<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>

推荐的方法

如果您使用的是 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>

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

String password = "p4ssword";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(password);
于 2013-09-06T09:14:45.663 回答
2

加盐哈希背后的原则是您不会受到彩虹表的影响。如果您使用静态盐,那么有人可以(但昂贵)为您的盐构建彩虹表。如果采摘是甜的,有人会这样做。

理想情况下,您的 salt 应该是随机的(例如,使用 a 中的字节SecureRandom)并且每个用户都应该不同。您应该将盐与散列密码一起存储,例如,如果您使用的是数据库表,那么只需有一个盐列。

Spring Security 的最新版本(3.1 及更高版本)尝试以自动、透明的方式处理 salt。密码编码器将自动生成随机盐并将其附加到散列而不是单独存储(例如在不同的列中)。因为散列和盐的长度是固定的,所以很容易确定数据的哪一部分是哪一部分。

于 2013-09-06T09:18:25.320 回答