PDA

Click to See Complete Forum and Search --> : md5 encryption


Pouncer
Feb 1st, 2007, 02:25 PM
Basically, i've imported this:

import java.security.*;

Then,
MessageDigest md = MessageDigest.getInstance("MD5");

creates the new instance of it. But im a bit unsure on the rest, i.e, the updating and digest etc? can someone show me how i can get a md5 encrypt of 'hello'

which would be

5d41402abc4b2a76b9719d911017c592

CornedBee
Feb 1st, 2007, 04:15 PM
MD5 encrypts binary data and results in a 128-bit binary number. So first you need to convert the string to binary, then you digest it, and finally, if you really need to, you convert it back to a string representation. (E.g. hexadecimal in your case.)
The thing about getting binary from a string is that you have to specify the encoding. I tend to use UTF-8.

String input = "hello";
byte[] data = input.getBytes("UTF-8");
byte[] digest = md.digest(data);
// Somehow convert back.
Now the thing is, this conversion takes another bit of code. All in all, it's a hassle. It's easier to download the Apache Jakarta Commons Codec library and just write
String hex = org.apache.commons.codec.digest.DigestUtils.md5Hex("hello");
The only shortcoming is that it doesn't let you specify the encoding.