Java Hash Calculate getHashWithSalt(String input, String algorithm, String salt)

Here you can find the source of getHashWithSalt(String input, String algorithm, String salt)

Description

This method hashes a string according to the desired message digest algorithm.

License

Open Source License

Parameter

Parameter Description
input the String to be hashed
algorithm the message digest algorithm that is used; one of MD5, SHA-1, SHA-256, SHA-512
salt a String to be used as a salt value

Exception

Parameter Description
UnsupportedEncodingException thrown only if UTF-8 is not supported (not likely)
NoSuchAlgorithmException thrown only if the algorithm requested for hashing isn'timplemented by the JCA (Java Cryptography Architecture)

Return

a String containing the hashed input

Declaration

public static String getHashWithSalt(String input, String algorithm, String salt)
        throws UnsupportedEncodingException, NoSuchAlgorithmException 

Method Source Code


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

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private static final int ITER = 1000;

    /**/* w  ww  . ja  va 2 s. c o  m*/
     * This method hashes a string according to the desired message digest
     * algorithm. The hash is salted and run multiple times.
     * 
     * @param input
     *            the String to be hashed
     * @param algorithm
     *            the message digest algorithm that is used; one of MD5, SHA-1,
     *            SHA-256, SHA-512
     * @param salt
     *            a String to be used as a salt value
     * @return a String containing the hashed input
     * @throws UnsupportedEncodingException
     *             thrown only if UTF-8 is not supported (not likely)
     * @throws NoSuchAlgorithmException
     *             thrown only if the algorithm requested for hashing isn't
     *             implemented by the JCA (Java Cryptography Architecture)
     */
    public static String getHashWithSalt(String input, String algorithm, String salt)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        digest.reset();
        digest.update(salt.getBytes("UTF-8"));
        byte[] bytes = digest.digest(input.getBytes("UTF-8"));
        for (int i = 0; i < ITER; i++) {
            digest.reset();
            bytes = digest.digest(bytes);
        }
        return new BigInteger(1, bytes).toString(16);
    }
}

Related

  1. getHashMDFive(String str)
  2. getHashOf(String s)
  3. getHashString()
  4. getHashString(byte[] data)
  5. getHashString(String password, String salt)
  6. hash()
  7. hash(Boolean value)
  8. hash(boolean value, int seed)
  9. hash(boolean[] array)