Hashing in Java

Hashing is a process of generate a one way string (hash) from a given string using mathematical function known as cryptographic hash. It is commonly use in generating a signature for file or text, and below is the sample how we create a hash using Java MessageDigest class.

For the list of supported algorithm for Java 9 may refer here

String input = "password";

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
		
System.out.println("Hash in byte -> " + new String(hash));

Console Output

Hash in byte -> ^ˆH˜Ú(qQÐåo?Æ)'s`=
j«½Ö*ïrBØ

At this point you may notice the generated result may not be readable by human, so we will have to transform it into hexadecimal format.

    StringBuilder hex = new StringBuilder();
    for (byte b : hash){
        hex.append(Integer.toHexString(0xff & b));
    }
    System.out.println("Hash in hex -> " + hex.toString());

Console Output

Hash in hex -> 5e884898da2847151d0e56f8dc6292773603dd6aabbdd62a11ef721d1542d8

Final Java Class

package my.cychew;

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

public class Hashing {

	public static void main(String[] args) throws NoSuchAlgorithmException {
		String input = "password";

		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
		
		System.out.println("Hash in byte -> " + new String(hash));
		
		//convert to hexadecimal
		StringBuilder hex = new StringBuilder();
		for (byte b : hash){
			hex.append(Integer.toHexString(0xff & b));
		}
		System.out.println("Hash in hex -> " + hex.toString());
	}
}
Hash in byte -> ^ˆH˜Ú(qQÐåo?Æ)'s`=
j«½Ö*ïrBØ
Hash in hex -> 5e884898da2847151d0e56f8dc6292773603dd6aabbdd62a11ef721d1542d8

Hashing in Java
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *