Skip to content

Instantly share code, notes, and snippets.

@0xffan
Last active August 21, 2017 06:44
Show Gist options
  • Save 0xffan/e01e7d5c02136d3aef47aa076392bec3 to your computer and use it in GitHub Desktop.
Save 0xffan/e01e7d5c02136d3aef47aa076392bec3 to your computer and use it in GitHub Desktop.
Generate MD5 digest in Java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
private static final char[] hexCode = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] data) {
if (data == null) {
return null;
}
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
public static String md5HexString(String param) {
MessageDigest algorithm;
try {
algorithm = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
algorithm.reset();
algorithm.update(param.getBytes());
byte[] messageDigest = algorithm.digest();
return toHexString(messageDigest);
}
public static void main(String[] args) {
System.out.println(MD5.md5HexString("123456"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment