Skip to content

Instantly share code, notes, and snippets.

@marlonlom
Last active March 10, 2016 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlonlom/9a6d42ece13fbeedde71 to your computer and use it in GitHub Desktop.
Save marlonlom/9a6d42ece13fbeedde71 to your computer and use it in GitHub Desktop.
package co.malm.demos.security.sha1;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Utility class that uses {@link MessageDigest} for obtaining a hashed text
* using algorithms such as MD5 and SHA-1
*
* @author marlonlom
*/
public class MessageDigestGenerator {
/**
* Generates a string with selected digest algorithm
*
* @param input
* text string to convert
* @param algorithm
* defined algorithm for use
* @return a generated hex string
* @throws NoSuchAlgorithmException
* if algorithm doesn't exists
*/
private static String digest(String input, final String algorithm)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] digested = md.digest(input.getBytes());
return new BigInteger(1, digested).toString(16);
}
/**
* Calculates the MD5 digest and returns the value as a hex string.
*
* @param input
* @return
* @throws Exception
*/
public static String md5(String input) throws Exception {
final String MD5 = "MD5";
return digest(input, MD5);
}
/**
* Calculates the SHA-1 digest and returns the value as a hex string.
*
* @param input
* @return
* @throws Exception
*/
public static String sha1(String input) throws Exception {
final String SHA1 = "SHA-1";
return digest(input, SHA1);
}
/**
* Calculates the SHA-256 digest and returns the value as a hex string.
*
* @param input
* @return
* @throws Exception
*/
public static String sha256(String input) throws Exception {
final String SHA256 = "SHA-256";
return digest(input, SHA256);
}
/**
* Calculates the SHA-512 digest and returns the value as a hex string.
*
* @param input
* @return
* @throws Exception
*/
public static String sha512(String input) throws Exception {
final String SHA512 = "SHA-512";
return digest(input, SHA512);
}
}
@marlonlom
Copy link
Author

How to use:
MessageDigestGenerator.sha256("wow, it works");
It prints > e609711a74800dfcae06f3adc3b7065439fd81892b5cf49fd2702835710bc19f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment