Sha2 password hash in Java

I tried to hash some passwords with Sha2

Where can I get a Java snippet?

I read that article, but I have some deficiencies: 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);
 }

Is this phrase the encoded string I want? What is the key (line 2)

Thank you in advance

Solution

First, you need to know what you want to do You say you want to hash the password, but the code you use is MAC (message authentication code), especially HMAC

Hashing and MAC are different purposes (although HMAC does involve using hashes) You need to make sure you use the correct one according to your requirements

The reason why the key is required is because the MAC needs a key Hash 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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>