java - 如何在 Spring Boot Security 中使用 HMAC-SHA512 对密码进行编码
问题描述
我有一个在 PHP 中运行的旧应用程序,它使用该函数base64_encode(hash_hmac(“sha512”, $p_password, $p_salt, true))
在我们的数据库中对密码进行编码。我正在将此应用程序迁移到 Java Spring Boot,并希望在身份验证期间以完全相同的方式对密码进行编码。
我在这篇文章Compute HMAC-SHA512 with secret key in java中找到了如何使用 Java 制作相同的哈希方法,我还了解到我们可以使用https://spring.io/blog为新老用户提供多个密码编码器/2017/11/01/spring-security-5-0-0-rc1-released#constructing-delegatingpasswordencoder
但是我仍然找不到如何在 Spring 身份验证过程中集成这种 hasing 方法的示例。我必须创建一个PasswordEncoder
bean,但我不知道在里面放什么。我尝试过Pbkdf2PasswordEncoder
,因为它可以像在我的应用程序中一样生成一些 SHA-512 哈希,但我得到了错误Detected a Non-hex character at 1 or 2 position
。这可能是由于数据库中的密码没有以 {pbkdf2} 为前缀。以下代码是我目前用作 PasswordEncoder 的代码
@Bean
public PasswordEncoder passwordEncoder() {
Pbkdf2PasswordEncoder passwordEncoder = new Pbkdf2PasswordEncoder("salt");
passwordEncoder.setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA512);
return passwordEncoder;
}
我需要帮助来设置正确的密码编码器,以便在我的 Java Spring 身份验证过程中使用 HMAC-SHA512,并在第二次将其与BCrytPasswordEncoder
(对于新用户)与DelegatingPasswordEncoder
. 也许它需要更新数据库中的密码以使用正确的编码器作为前缀?
如果我的问题不够准确或缺少信息,请向我询问更多详细信息:)
解决方案
您需要将 DelegatingPasswordEncoder 添加到项目配置文件中。DelegatingPasswordEncoder 充当 PasswordEncoder,当我们必须从一组实现中进行选择时,我们会使用它:
@Configuration
public class ProjectConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
Map<String, PasswordEncoder> encoders = new HashMap<>();
Pbkdf2PasswordEncoder bcryprPe = new Pbkdf2PasswordEncoder("salt");
bcryprPe.setAlgorithm(
Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA512);
encoders.put("pbkdf2", pbkdf2Pe);
// add other PasswordEncoder here:
encoders.put("scrypt", new SCryptPasswordEncoder());
return new DelegatingPasswordEncoder("pbkdf2", encoders);
}
}
和
return new DelegatingPasswordEncoder("pbkdf2", encoders);
我们对 Spring Security 说:“使用 'pbkdf2' 作为默认密码编码器”。
如果提供的哈希是 {scrypt}12345,则 DelegatingPasswordEncoder 委托给 SCryptPasswordEncoder,如果没有前缀,应用程序将使用默认值。
推荐阅读
- vue.js - Vue 倒数计时器会在 console.log 上打印出来,但不会作为数据传递
- javascript - 将混合心情与黑色文本混合
- sql - 如果不存在关系,SQL 删除行
- javascript - JS - 过滤 Promise 对象
- multithreading - 使用 vs2017 时 std::thread::join() 在某些情况下挂起
- python - 如何解决 django 错误:raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
- react-native - 如何在 react-native for android 中更改应用程序图标背景颜色
- python - Python查找多个字符串
- ios - 如何在 iOS 中找到自定义 UTI 应用程序支持?
- javascript - Get desktop file icons using NodeJs