Spring Security - 密码哈希

时间:2015-05-10 12:36:07

标签: java spring security spring-mvc hash

我使用Spring Security来处理我的应用程序中的授权。在我的配置中,我有以下内容:

<security:authentication-manager>  
    <security:authentication-provider>  
        <security:password-encoder hash="md5"/>  
        <security:jdbc-user-service id="userService"
                    data-source-ref="dataSource"
                    users-by-username-query="select phone, password, true from users where phone=?"
                    authorities-by-username-query="select phone,'ROLE_USER' from users where phone=?" />
    </security:authentication-provider>  
</security:authentication-manager> 

当我删除<security:password-encoder hash="md5"/>行并存储在DB原始密码中时,授权正常。但是,当我尝试在数据库中存储密码并使用此行时,授权失败。我做错了吗?

P.S。 DB中的密码哈希是100%正确的。 202cb962ac59075b964b07152d234b70密码123

1 个答案:

答案 0 :(得分:2)

我建议你创建Test类,然后创建hash。

  import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

    public class Test {
        public static void main(String[] args) {
            Md5PasswordEncoder encoderMD5 = new Md5PasswordEncoder();
            String securePass = encoderMD5.encodePassword("admin", null);
            System.out.println(encoderMD5.isPasswordValid(securePass,"admin", null));
        }
    }

在xml中使用

<bean name="md5" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>

<security:password-encoder ref="md5"/>

当然,检查数据库中的哈希密码值

我建议使用 bcrypt

在xml中

<bean name="bcryptEncode" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <constructor-arg value="12"></constructor-arg>
</bean>

<security:password-encoder ref="bcryptEncode"/>

您可以通过以下方式获得编码密码:

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class PrintBCryptString {
    public static void main(String[] args) {
        PasswordEncoder encoder = new BCryptPasswordEncoder(12);
        System.out.println(encoder.matches("type here some string", encoder.encode("type here some string")));
        System.out.println(encoder.encode("type here some string"));
    }
}

也许有用的小explanation of bcrypt