java中的SHA2密码哈希 [英] SHA2 password hashing in java

查看:178
本文介绍了java中的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 =;
(字节b:shaDigest){
hash + = String.format(%02x,b);
}

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

在此先感谢

解决方案

<首先,你需要清楚你想要做什么。你说你想散列一个密码,但是你使用的代码是用于MAC(消息认证码 a>),特别是 HMAC



<对于不同的目的,哈希和MAC是不同的东西(尽管HMAC确实涉及使用哈希)。你需要确保你的要求是正确的。



你被要求提供密钥的原因是因为MAC需要一个密钥。哈希不会:

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


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

解决方案

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:

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天全站免登陆