Hy guys!
I have the following problem: I need to hash an unsigned byte in Java which is(would be...) between 0-255. The main problem is that java doesnt have an unsigned Byte type at all. I found a workaround for this, and used int instead of byte with a little modification.
The main problem is: Java.securitys Messagedigest.digest function only accepts byte array types, but i would need to give it an int array.
Anybody has a simpe workaround for this? I was looking for a third party sha-1 function, but didnt found any. Nor any sample code.
So basically what i need: I have an unsigned byte value for example: 0xFF and need to get the following sha1 hash: 85e53271e14006f0265921d02d4d736cdc580b0b
any help would be greatly appreciated.
It's important to understand that there is no difference between signed and unsigned bytes with respect to their representation. Signedness is about how bytes are treated by arithmetic operations (other than addition and subtraction, in the case of 2's complement representation).
So, if you use
byte
s for data storage, all you need is to make sure that you treat them as unsigned when converting values tobyte
s (use explicit cast with(byte)
, point 1) and frombyte
s (prevent sign extension with& 0xff
, point 2):The digest won't care about how Java perceives the sign of a byte; it cares only about the bit pattern of the byte. Try this:
This should print
85e53271e14006f0265921d02d4d736cdc580b0b
.Look at Apache Commons Codec library, method DigestUtils.sha(String data). It may be useful for you.