Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Last active August 29, 2015 14:23
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 wszdwp/601f2bcbc79474deb702 to your computer and use it in GitHub Desktop.
Save wszdwp/601f2bcbc79474deb702 to your computer and use it in GitHub Desktop.
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