Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

hash - SHA2 password hashing in java

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...