Last active
August 21, 2017 06:44
-
-
Save 0xffan/e01e7d5c02136d3aef47aa076392bec3 to your computer and use it in GitHub Desktop.
Generate MD5 digest in Java
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
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