Java Hash Calculate getHash(String password, String salt)

Here you can find the source of getHash(String password, String salt)

Description

Calculates the hash of a password and salt using SHA-256.

License

Open Source License

Parameter

Parameter Description
password - password to hash
salt - salt associated with user

Return

hashed password, or null if unable to hash

Declaration

public static String getHash(String password, String salt) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.math.BigInteger;
import java.security.MessageDigest;

public class Main {
    /**//from  w  w w. j a v  a 2s  .  co  m
     * Calculates the hash of a password and salt using SHA-256.
     * 
     * @param password
     *            - password to hash
     * @param salt
     *            - salt associated with user
     * @return hashed password, or null if unable to hash
     */
    public static String getHash(String password, String salt) {
        String salted = salt + password;
        String hashed = salted;

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(salted.getBytes());
            hashed = encodeHex(md.digest(), 64);
        } catch (Exception ex) {
            hashed = null;
        }

        return hashed;
    }

    /**
     * Returns the hex encoding of a byte array.
     * 
     * @param bytes
     *            - byte array to encode
     * @param length
     *            - desired length of encoding
     * @return hex encoded byte array
     */
    public static String encodeHex(byte[] bytes, int length) {
        BigInteger bigint = new BigInteger(1, bytes);
        String hex = String.format("%0" + length + "X", bigint);

        assert hex.length() == length;
        return hex;
    }
}

Related

  1. getHash(String pass, String algorithm)
  2. getHash(String password, byte[] salt)
  3. getHash(String password, byte[] salt)
  4. getHash(String password, String bsalt)
  5. getHash(String password, String salt)
  6. getHash(String phrase, String algorithm)
  7. getHash(String s)
  8. getHash(String str, String algorithm)
  9. getHash(String strDate)