Reputation: 21
Ok all here is my problem. I am attempting to encrypt a string with the MD5 hash. Here is the string I am attempting to hash: NjljNWZjZWJhYTY1YjU2MGVhZjA2YzNmYmViNDgxYWU0NGI4ZDYxOA==
Here is the expected output: aaf53a928ca9baa6df03a5fe6e3c7b71
And here is what I am getting in my Android application: 3cc9a8b9d101349af1b4e17ae3b7450f
Now here is my code I am using to do this:
public final String computeMD5Hash(final String pass){
try {
// Create MD5 Hash
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(pass.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
System.out.println(hexString.toString());
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
With this code running on Android I get the unexpected result above, but when I run this code just as a java program passing in the same string I get the expected output...
What on earth is going on? I have been stumped on this for days and scoured the Internet for a clue. I have tried changing the bytes to and from UTF-8, ASCII, ISO-8859-1, and using the default. Always getting the same string that is incorrect.
-----------Edit----------Solution------
I figured it out, I was using Base64.encodeToString(bytes, Base64.Default) what I should have been using the Base63.NO_WRAP flag option... a newline was being entered and throwing everything off. Thanks all
Upvotes: 1
Views: 1737
Reputation:
It appears you must be passing in the wrong string. I just ran your code myself and the output was: aaf53a928ca9baa6df03a5fe6e3c7b71
I directly set the string passed in to the one you provided.
Test it out for yourself. Remove the final String and explicitly set the value of pass to NjljNWZjZWJhYTY1YjU2MGVhZjA2YzNmYmViNDgxYWU0NGI4ZDYxOA==
Upvotes: 1