java中的SHA2密码散列 [英] SHA2 password hashing in java

查看:35
本文介绍了java中的SHA2密码散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 SHA2 对一些密码进行哈希处理.

I'm trying to hash some passwords with SHA2.

我在哪里可以得到一段 Java 代码来制作它?

Where can I get a snippet of java code for make that?

我看过那个帖子,但我缺少一些东西:使用 Java 存储 SHA2 密码

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);
 }

这句话是我想要编码的字符串吧?什么是关键(第 2 行)

The phrase is the String I want encode right? And what is the key (line 2)

提前致谢

推荐答案

首先,你需要明确你想要做什么.你说你想散列一个密码,但你使用的代码是用于 MAC (消息身份验证代码),特别是 HMAC.

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.

哈希和 MAC 出于不同目的是不同的东西(尽管 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.

要求您提供密钥的原因是 MAC 需要密钥.哈希不会:

The reason you are being asked to supply a key is because MACs need a key. Hashes do not:

public byte[] hash(String password) throws NoSuchAlgorithmException {
    MessageDigest sha256 = MessageDigest.getInstance("SHA-256");        
    byte[] passBytes = password.getBytes();
    byte[] passHash = sha256.digest(passBytes);
    return passHash;
}

这篇关于java中的SHA2密码散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆