3

I'm trying to hash a number, represented by hex string with Java security library. Meaning, If I have the String "AABBCCDD" I want to hash it not as this is an ascii input, which is 0x65, 0x65, 0x66, 0x66, 0x67, 0x67, 0x68, 0x68, but as four bytes - 0xAA, 0xBB, 0xCC, 0xDD. I managed to do it with low values such as "112233445566" (since bytes are signed in Java) but failed with high values.

Does someone know how to implement such thing?

Thanks, Binyamin

MByD
  • 135,866
  • 28
  • 264
  • 277
  • These isn't a method that take `byte[]` as input? I'm not quite sure I understand what the problem is. –  Dec 02 '10 at 07:39
  • Yes it is. I assume I made some mistakes in my implementation before. – MByD Dec 02 '10 at 08:10

2 Answers2

6

First convert your hex into byte[] using for example this: Convert a string representation of a hex dump to a byte array using Java?

After it use

byte[] data = hexStringToByteArray(hexData);
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(data, 0, data.length);
byte[] sha1hash = md.digest();
Community
  • 1
  • 1
gleber
  • 4,392
  • 1
  • 26
  • 28
  • I actually already implemented hexStringToByteArray() before for RC4 implementation, but for some reason I forgot it exists and tried to solve it in a different (way more complicated and inefficient way). Thanks. – MByD Dec 02 '10 at 08:08
  • Why are you creating a byte array and then effectively discarding it? Just declare sha1Hash on the final line when you call `md.digest()`. – Jon Skeet Dec 02 '10 at 08:32
  • (Fixed the odd use of `text.length()` too.) – Jon Skeet Dec 02 '10 at 08:32
  • Indded, fixed sha1hash blunder – gleber Dec 02 '10 at 09:46
2

Basically you just need to find a hex parser - there are plenty around, with one example here, or Apache Commons Codec for this and other conversions. While Java bytes are indeed signed, you'll get the same bit pattern as if they were unsigned, so they'll have the same way. Unless you're performing your own arithmetic/bit-shifting on byte values, you can usually ignore the fact that bytes are signed in Java.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194