• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java MD5 hashed string doesn't match the one given by md5sum command

 
Leon scott
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

I need your help, i want to hash a string with java. Here is the code i use :


public static void main(String[] args)throws Exception
{
String password = "testtest";

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());

byte byteData[] = md.digest();

StringBuffer hexString = new StringBuffer();
for (int i=0;i<byteData.length;i++) {
String hex=Integer.toHexString(0xff & byteData[i]);
if(hex.length()==1) hexString.append('0');
hexString.append(hex);
}
System.out.println(hexString.toString());
}

The result obtained is : 05a671c66aefea124cc08b76ea6d30bb

The problem is that this result is different from the one given by md5sum on Ubuntu

# echo testtest | md5sum
199389a12492266114933fc428e8cfdc -

Can anyone tell me what it is wrong with my code to get a different hash for the same string ?

Thanks in advance for your responses.
 
Leon scott
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found the problem : my java code was OK, the problem comes from the echo command that adds a newline caracter to the string to be hashed.
Use the command below instead :
# echo -n testtest | md5sum
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right, MD5 and SHA* are defined on octets (unsigned bytes) and any changes will give you different results.

Most programatic usages have to decide whether or not to include line endings, and if so, what line endings to use. OS-X and Linux use different line endings than Windows.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic