Last active
March 10, 2016 01:48
-
-
Save marlonlom/9a6d42ece13fbeedde71 to your computer and use it in GitHub Desktop.
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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use:
MessageDigestGenerator.sha256("wow, it works");
It prints > e609711a74800dfcae06f3adc3b7065439fd81892b5cf49fd2702835710bc19f