Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Leading Zeroes disappearing whilst hashing

 
Iain Emsley
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47293
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47293
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell. I got it working with:
 
Campbell Ritchie
Sheriff
Pie
Posts: 47293
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome. Clever little trick with substring(1)
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic