java中的SHA2密码散列
我正在尝试使用 SHA2 对一些密码进行哈希处理。
我在哪里可以得到一段java代码来实现这一点?
我看过那个帖子,但我缺少一些东西: 使用 Java 进行 SHA2 密码存储
Mac mac = Mac.getInstance("HmacSha256");
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), "HmacSha256");
mac.init(secret);
byte[] shaDigest = mac.doFinal(phrase.getBytes());
String hash = "";
for(byte b:shaDigest) {
hash += String.format("%02x",b);
}
该短语是我想要编码的字符串,对吧?关键是什么(第 2 行)
提前致谢
I'm trying to hash some passwords with SHA2.
Where can I get a snippet of java code for make that?
I have seen that post but I have something missing:
SHA2 password storage with Java
Mac mac = Mac.getInstance("HmacSha256");
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), "HmacSha256");
mac.init(secret);
byte[] shaDigest = mac.doFinal(phrase.getBytes());
String hash = "";
for(byte b:shaDigest) {
hash += String.format("%02x",b);
}
The phrase is the String I want encode right? And what is the key (line 2)
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,你需要明确你想做什么。您说您想要对密码进行哈希处理,但您使用的代码适用于 MAC(消息身份验证代码),具体来说,HMAC。
哈希值和 MAC 是用于不同目的的不同事物(尽管 HMAC 确实涉及使用哈希值)。您需要确保您使用的是符合您要求的正确产品。
要求您提供密钥的原因是 MAC 需要密钥。哈希不会:
First, you need to be clear what it is you want to do. You say you want to hash a password, but the code you are using is for a MAC (Message Authentication Code), specifically, HMAC.
Hashes and MACs are different things for different purposes (though HMAC does involve using a hash). You need to be sure you are using the right one for your requirement.
The reason you are being asked to supply a key is because MACs need a key. Hashes do not:
我修改了一点rossum的代码,添加了salt并将返回类型转换为String,添加了try/catch,也许这会对某人有所帮助:
I modified a little rossum's code, added salt and convert returning type to String, add try/catch, maybe it will help to someone:
您可以考虑使用 commons-codec 的实现
you may consider using commons-codec's implementation
短语是您要保护的密码。
key
是盐,是在散列之前附加到密码的唯一(且已知)字符串,以击败彩虹表。或者至少应该是。您的代码只是从密码本身获取它,这是毫无意义的。它应该是一个长随机字符串,与密码摘要一起存储。Phrase would be the password that you're trying to protect.
key
is the salt, a unique (and known) string appended to your password before hashing, to defeat rainbow tables. Or it should be, at least. Your code is just taking it from the password itself, which is kind of pointless. It should be a long random string that is stored together with the password digest.