java - Spring Security - 密码哈希

标签 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"/>时行并存储在数据库原始密码中,授权工作正常。但是当我尝试在数据库中存储哈希密码并使用此行时,授权失败。我做错了什么吗?

附注数据库中的密码哈希值 100% 正确。 202cb962ac59075b964b07152d234b70对于 123密码。

最佳答案

我可以建议您创建测试类并创建哈希。

  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

关于java - Spring Security - 密码哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151491/

相关文章:

java - GXT 网格行不可选择

java - Android - 使用位图的 AsyncTask - OutOfMemoryError

java - 如果服务器上的 Java 评估 Javascript,则会出现安全问题

c++ - 如何确保编译器优化不会带来安全风险?

security - JsonWebToken : activity-based expiration vs issuing time-based expiration

java - 重写代码以仅获取几个变量

java - 如何在 Hibernate 中通过第三个实体将一个实体连接到第二个实体?

java - Autowiring 时始终提供接口(interface)?

spring - Spring Boot 中的全局方法安全性

java - 访问未在 Clojure 中导入的 Java 类的字段和方法