Android How to - Generates a SHA-1 hash of password and salt and returns it as hex-encoded string








Question

We would like to know how to generates a SHA-1 hash of password and salt and returns it as hex-encoded string.

Answer

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*from  w  ww .  j  ava 2  s  .  c om*/
import android.util.Log;


public class Main{
  /**
   * Generates a SHA-1 hash of password and salt and returns it as hex-encoded string.
   * @param password the password to encrypt
   * @param salt random string that should be used to salt the password
   * @return hex-encoded string of hash
   */
  public static String encryptPassword(String password, String salt) {
    final String algorithm = "SHA-1";
    try {
      MessageDigest digester = MessageDigest.getInstance(algorithm);
      byte[] saltedPassword = (password + salt).getBytes();
      byte[] hash = digester.digest(saltedPassword);
      
      return String.format("%040x",new BigInteger(1, hash));
    } catch (NoSuchAlgorithmException e) {
      return null;
    }
  }
}