问题
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.
回答1:
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 to byte
s (use explicit cast with (byte)
, point 1) and from byte
s (prevent sign extension with & 0xff
, point 2):
public static void main(String[] args) throws Exception {
byte[] in = { (byte) 0xff }; // (1)
byte[] hash = MessageDigest.getInstance("SHA-1").digest(in);
System.out.println(toHexString(hash));
}
private static String toHexString(byte[] in) {
StringBuilder out = new StringBuilder(in.length * 2);
for (byte b: in)
out.append(String.format("%02X", b & 0xff)); // (2)
return out.toString();
}
回答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:
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update((byte) 0xFF);
byte[] result = digest.digest();
StringBuilder buffer = new StringBuilder();
for (byte each : result)
buffer.append(String.format("%02x", 0xFF & each));
System.out.println(buffer.toString());
This should print 85e53271e14006f0265921d02d4d736cdc580b0b
.
回答3:
Look at Apache Commons Codec library, method DigestUtils.sha(String data). It may be useful for you.
来源:https://stackoverflow.com/questions/9066835/java-sha-1-hash-an-unsigned-byte