Created
February 1, 2018 07:52
-
-
Save MilanSavaliya/e535494306a2324399445935420c97e8 to your computer and use it in GitHub Desktop.
Sample Program to Show how to calculate Hash value using MD5 and SHA1 in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.causecode.sample; | |
import javax.xml.bind.annotation.adapters.HexBinaryAdapter; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.util.Scanner; | |
/** | |
* Demo Program to show how to calculate the hash code for the given input | |
*/ | |
public class Main { | |
/** | |
* Enum representing Algorithms | |
*/ | |
private enum Algorithm { | |
MD5, | |
SHA1 | |
} | |
/** | |
* Main Entry Point for Java JVM | |
* @param args | |
* @throws NoSuchAlgorithmException | |
*/ | |
public static void main(String[] args) throws NoSuchAlgorithmException { | |
Scanner scanner = new Scanner(System.in); | |
printToConsole("Enter the input to calculate the hash ? "); | |
String input = scanner.nextLine(); | |
printToConsole("----------------------"); | |
printToConsole("Chose Algorithm.."); | |
printToConsole("1) MD5"); | |
printToConsole("2) SHA1"); | |
int choice = scanner.nextInt(); | |
scanner.close(); | |
String hash; | |
if (choice == 1) { | |
hash = calculateHash(input, Algorithm.MD5); | |
} else { | |
hash = calculateHash(input, Algorithm.SHA1); | |
} | |
printToConsole("----------------------"); | |
printToConsole(String.format("Calculated Hash for Given Input is:- \" %s \"", convertHashToHexString(hash))); | |
} | |
/** | |
* Convert Given Hash to Hex Representation | |
* @param hash | |
* @return String | |
*/ | |
private static String convertHashToHexString(String hash) { | |
return new HexBinaryAdapter().marshal(hash.getBytes()); | |
} | |
/** | |
* Calculates the hash for the given input using supplied Algorithm | |
* @param message | |
* @param algorithm | |
* @return | |
* @throws NoSuchAlgorithmException | |
*/ | |
static String calculateHash(String message, Algorithm algorithm) throws NoSuchAlgorithmException { | |
return String.valueOf(MessageDigest.getInstance(algorithm.toString()).digest(message.getBytes())); | |
} | |
/** | |
* Utility Method to print line to the console | |
* @param message | |
*/ | |
static void printToConsole(String message) { | |
System.out.println(message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment