Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm trying to generate an MD5 hash using Java and Shell but the problem is I get different results using :
public String generateHash(String name) throws UnsupportedEncodingException, NoSuchAlgorithmException {
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(name.getBytes());
byte[] md5Bytes = digester.digest();
String md5Text = null;
md5Text = bytesToHex(md5Bytes);
return md5Text;
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
return new String(hexChars);
and using :
md5sum
How can I get the same result as the "md5sum" command in Java ?
Under the assumption that
private static final char[] hexArray = "0123456789abcdef".toCharArray();
both methods, i.e. you program and md5sum, produce the same result. Be careful to not accidentaly add any newlines.
You can compare the result of both of these example to check that you get the same output:
System.out.println(generateHash("ABCDEF"));
System.out.println(generateHash("ABCDEF\n"));
echo -n "ABCDEF" | md5sum
echo "ABCDEF" | md5sum
Output:
8827a41122a5028b9808c7bf84b9fcf6
f6674e62795f798fe2b01b08580c3fdc
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.