Skip to content

Instantly share code, notes, and snippets.

@wszdwp wszdwp/MD5HashingExample
Last active Aug 29, 2015

Embed
What would you like to do?
MD5 HASH in Java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5HashingExample
{
//Version 1
public static String getHash1(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if(hex.length()==1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
//Version 2
public static String getHash2(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++) {
hexString.append(Integer.toString((messageDigest[i] & 0xff) + 0x100, 16).substring(1));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args)throws Exception
{
String password = "2l26k2ncmt1ptdvl60e5tpdlqqmd5 hash is not safe!20150622170627";
System.out.println("MD5Digest(in hex format): " + getHash1(password));
System.out.println("MD5Digest(in hex format): " + getHash2(password));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.