File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Security and the fly likes my code gives the wrong hash value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » Security
Bookmark "my code gives the wrong hash value" Watch "my code gives the wrong hash value" New topic

my code gives the wrong hash value

Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

I'm trying to follow directions to generate a hash of a string to get the "digestValue" portion of a digitally signed XML file.

the code below works and gives me a string. but the string doesn't match the digestValue in the xml example file, part of which is given below.
I guess my main question: Is MessageDigest the correct class to be using in this situation?

xml file I'm trying to match:

finally, here are the instructions I am trying to follow:
1) Apply a hash algorithm over the specified content to be digitally signed. In this case, the content to be signed is <wsu:Timestamp>. The hash algorithm that is used is SHA-1. The result of the hashing operation is stored in the DigestValue. The SHA-1 hash value is 160 bits in length and when converted into Base64 it is precisely 28 characters, which is exactly what you see in DigestValue.
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
Could it be a matter of whitespace? In the Java app, you're concatenating the elements w/o line breaks, while the XML you quote has them, as well as leading spaces in the two lines in the middle.
Robin Wilson

Joined: May 10, 2006
Posts: 22
It is almost certainly related to whitespace... The information you are supposed to be hashing is explicitly the 4 lines specified. However, you are manually selecting 4 separate strings, without getting all the whitespace in the 4 specified lines. You are missing "\n" at the end of the first 3 lines, then " " at the beginning of lines 2 and 3... That does make a difference.

(Keep in mind that simply because you can't see a character doesn't mean it isn't there - and if it is there, it has a value that will significantly alter the resulting hash value. We see a file as a series of independent "lines" of data. The computer sees a file as a continuous stream of bit (bytes), including the bytes that represent line breaks and leading/trailing spaces.)

--<br />Robin D. Wilson
Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

Thank you, guys.
That was it.
In fact, there is a step called "canonicalization" or "c14n" that I was missing. It must be done when signing things. This is handled by the WSS4J libraries and it strips whitespace before signing an element.
I agree. Here's the link:
subject: my code gives the wrong hash value
jQuery in Action, 3rd edition