wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Leading Zeroes disappearing whilst hashing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Leading Zeroes disappearing whilst hashing" Watch "Leading Zeroes disappearing whilst hashing" New topic
Author

Leading Zeroes disappearing whilst hashing

Iain Emsley
Ranch Hand

Joined: Oct 11, 2007
Posts: 60
I'm trying to write a script which compares an SHA1 hash with an equivalent in a database for a login application and its largely going well but it is dropping the leading zeroes which means that it is failing the test. I'd be grateful for any pointers as to how to solve this.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38340
    
  23
Not familiar with the Integer.toHexString() method; does it have enough digits in for an SHA1?

But the Integer.toBinaryString() method always misses out leading zeroes; if I want them, I end up writing a for loop with System.out.print(0); in. I presume you are having a similar problem with toHexString(). More details of that method, which are worth checking, here.
Iain Emsley
Ranch Hand

Joined: Oct 11, 2007
Posts: 60
Thanks. It appears to be the toHexString method that's failing. I'll check out the docs as well. Just wondering it would be easier to not use a hex string in the original hash and just compare them. I can but give it a go.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38340
    
  23
Try a StringBuilder. Get your hex string, and it will have 8 characters in.With a StringBuilder, you can insert all your 8-character hex Strings at 0, then the leading 0s, if you put them in reverse order!

Check the StringBuilder API documentation for the insert method, in case it should be insert("0", 0).
Iain Emsley
Ranch Hand

Joined: Oct 11, 2007
Posts: 60
Thanks Campbell. I got it working with:
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38340
    
  23
You're welcome. Clever little trick with substring(1)
 
wood burning stoves
 
subject: Leading Zeroes disappearing whilst hashing