弹簧安全>5.0.0删除了Md5PasswordEncoder

2022-09-04 00:44:41

我有一个使用Spring安全性的Spring项目。我使用的是Spring Boot 1.5,现在我迁移到Spring Boot 2.0。

我注意到Md5PasswordEncoder在Spring Security的最终版本中已被删除。相反,即使已弃用(https://docs.spring.io/spring-security/site/docs/5.0.3.RELEASE/api/),仍然存在。Md4PasswordEncoder

我应该使用外延 MD5 编码器还是将分类移动到其他位置?


答案 1

不复存在的事实并不意味着Spring Security 5无法创建哈希值。它用于此。Md5PasswordEncoderMD5new MessageDigestPasswordEncoder("MD5")

有两个选项,都与new一起使用,它期望密码前缀来确定哈希算法,例如:DelegatingPasswordEncoder{MD5}password_hash

默认密码编码器设置为(大写!),因此如果密码没有前缀,则应用默认编码器:MD5

PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
passwordEncoder.setDefaultPasswordEncoderForMatches(new MessageDigestPasswordEncoder("MD5"));

或者,在数据库中的现有密码哈希值前面加上前缀。通过这种方式,“MD5”的代表们已经离开了。像这样:{MD5}DelegatingPasswordEncoder

update myusertable set pwd = '{MD5}' || pwd;

答案 2

如果你想使用MD5,你可以自定义:

@Bean
public PasswordEncoder passwordEncoder() {
    return new PasswordEncoder() {
        @Override
        public String encode(CharSequence charSequence) {
            return getMd5(charSequence.toString());
        }

        @Override
        public boolean matches(CharSequence charSequence, String s) {
            return getMd5(charSequence.toString()).equals(s);
        }
    };
}

public static String getMd5(String input) {
    try {
        // Static getInstance method is called with hashing SHA
        MessageDigest md = MessageDigest.getInstance("MD5");

        // digest() method called
        // to calculate message digest of an input
        // and return array of byte
        byte[] messageDigest = md.digest(input.getBytes());

        // Convert byte array into signum representation
        BigInteger no = new BigInteger(1, messageDigest);

        // Convert message digest into hex value
        String hashtext = no.toString(16);

        while (hashtext.length() < 32) {
            hashtext = "0" + hashtext;
        }

        return hashtext;
    }

    // For specifying wrong message digest algorithms
    catch (NoSuchAlgorithmException e) {
        System.out.println("Exception thrown"
                + " for incorrect algorithm: " + e);
        return null;
    }
}

推荐