How to hash a password with SHA-512 in Java?

you can use this for SHA-512 (Not a good choice for password hashing).

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public String get_SHA_512_SecurePassword(String passwordToHash, String salt){
    String generatedPassword = null;
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-512");
        md.update(salt.getBytes(StandardCharsets.UTF_8));
        byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for(int i=0; i< bytes.length ;i++){
            sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        generatedPassword = sb.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return generatedPassword;
}

Use Apache Commons Crypt, it features SHA-512 based crypt() functions that generate salted hashes that are even compatible to libc's crypt and thus usable in PHP/Perl/Python/C and most databases, too.

https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/digest/Crypt.html#Crypt%28%29


Please stop using hash functions to encode passwords! They do not provide the protection you need. Instead, you should be using an algorithm like PBKDF2, bcrypt, or scrypt.

References:

  • http://blog.tjll.net/please-stop-hashing-passwords/
  • http://security.blogoverflow.com/2011/11/why-passwords-should-be-hashed/
  • https://crackstation.net/hashing-security.htm
  • http://www.sitepoint.com/risks-challenges-password-hashing/
  • http://security.blogoverflow.com/2013/09/about-secure-password-hashing/

Using Guava:

Hashing.sha512().hashString(s, StandardCharsets.UTF_8).toString()