hash of string java

Solutions on MaxInterview for hash of string java by the best coders in the world

showing results for - "hash of string java"
Marvin
01 Sep 2018
1// Needed imports
2import java.security.MessageDigest;
3import java.security.NoSuchAlgorithmException;
4
5// Return the hash for the given string using the specified hashing algorithm (hashType)
6// Usable algorithms include: "MD5", "SHA-256", "SHA3-256"
7public static String getStringHash(String str, String hashType) throws NoSuchAlgorithmException
8{
9	// hash string into byte array
10	MessageDigest md = MessageDigest.getInstance(hashType);
11	byte[] hashbytes = md.digest(str.getBytes());
12
13	// convert byte array into hex string and return
14	StringBuffer stringBuffer = new StringBuffer();
15	for (int i = 0; i < hashbytes.length; i++) {
16		stringBuffer.append(Integer.toString((hashbytes[i] & 0xff) + 0x100, 16)
17			.substring(1));
18	}
19	return stringBuffer.toString();
20}