问题描述
我需要一些关于需要检查来自 UI 表单(即 Authentication
对象)的密码的场景的指导,我需要使用 SHA-256 + 常量盐进行散列
(在进行比较之前)和密码来自使用 Spring Security 的 DB(DB 也有散列密码 + salt).
I need some guidance on the scenario where I need to check the password coming from UI form (i.e, Authentication
object) which I need to hashed using SHA-256 + constant salt
(before making comparison) and password coming from DB (DB also has hashed password + salt) using Spring Security.
我希望比较使用相同 SALT 值生成的这两个 不同 散列值.我们如何在java中做到这一点?谁能分享一个示例代码?
I am looking to compare these two different hashed value generated using same SALT value. How we can do it in java? Could anyone please share me a sample code?
推荐答案
你可以简单地比较两个密码字符串 passwordA.equals(passwordB)
...
You could simply compare the two password strings passwordA.equals(passwordB)
...
这有一些安全缺陷:
密码不应作为字符串处理,而应作为字符或字节数组处理:看看这里为什么
相等比较(理论上)容易受到定时攻击:查看有关 java 中解决方案的讨论
An Equal comparison is (theoretically) vulnerable to a timing-attack: see a discussion about a solution in java
使用标准工具来做与安全相关的事情可能是明智的(即使它们看起来很简单).Spring Security 有大量工具可以为您做到这一点.看看 BCryptPasswordEncoder 例如.出于安全目的使用经过良好测试和维护的框架始终是一个好主意.
It might be wise to use standard-tool to do security related things (even when they seem to be simple). Spring security has a ton of tools that can do that for you. Have a look at BCryptPasswordEncoder for example. Using well tested and maintained frameworks for security purposes is always a good idea.
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
...
boolean result = passwordEncoder.matches(rawPassword, hashedPassword);
还有:使用正确的密码散列算法!有关某些建议,请参阅 SO 上的此答案
Also: Use a proper Algorithm for Password-Hashing! See this Answer on SO for some proposals
SHA-256 不是其中之一.Spring Security 为您提供了适合作业的工具,因此您可以直接使用它们.
SHA-256 is not one of them. Spring Security gives you the right tools for the jobs, so you could just use them.
这篇关于使用Java,Spring安全性中的SHA-256算法使用相同的盐比较两个散列密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!