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
In
http://www.anyexample.com/programming/java/java_simple_class_to_compute_md5_hash.xml
an example is given how to calculate an MD5 hash of String. This results in a 20 digit hex string. According to
http://en.wikipedia.org/wiki/MD5
I would expect a 32 digit hex string. I get the same result for example using dac2009 response in
How can I generate an MD5 hash?
.
Why do I get something which looks like a MD5 hash but isn't? I cannot imagine that all the strings I get I have to pad with 12 leading zeros.
Edit: one code example
public static String MungPass(String pass) throws NoSuchAlgorithmException {
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] data = pass.getBytes();
m.update(data,0,data.length);
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032X", i);
Taken from http://snippets.dzone.com/posts/show/3686
–
–
–
–
–
You must be missing something. The linked code is just fine. Make sure the issue is nowhere else, related to displaying the result. Possibilities:
in a GUI too small
in a console with multithreading issues
over a network package which is being cut off to soon
you cut the length to 20
instead of 0x20
, which is 32
.
–
–
–
–
You can use DatatypeConverter.printHexBinary(digiest) to get the 128 bit hash represented by 32 hexadecimal numbers. Below is the complete code snippet to generate MD5 hash in Java,
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class MD5HashGenerator
public static void main(String args[]) throws NoSuchAlgorithmException
String stringToHash = "MyJavaCode";
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(stringToHash.getBytes());
byte[] digiest = messageDigest.digest();
String hashedOutput = DatatypeConverter.printHexBinary(digiest);
System.out.println(hashedOutput);
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.