Skip to content

Instantly share code, notes, and snippets.

@manuelbrunner
Created September 25, 2012 09:22
Show Gist options
  • Save manuelbrunner/3780814 to your computer and use it in GitHub Desktop.
Save manuelbrunner/3780814 to your computer and use it in GitHub Desktop.
// includes http://stackoverflow.com/questions/332079/in-java-how-do-i-convert-a-byte-array-to-a-string-of-hex-digits-while-keeping-l
public static void main(String[] args) throws Exception {
String stringToEncrypt = "foobar";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(stringToEncrypt.getBytes("UTF-8"));
byte messageDigest[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0;i<messageDigest.length;i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if (hex.length() == 1) {
// could use a for loop, but we're only dealing with a single byte
hexString.append('0');
}
hexString.append(hex);
}
System.out.println(hexString.substring(0, 10));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment