Java SHA-1 hash an unsigned BYTE

2020-08-01 05:05发布

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.

3条回答
beautiful°
2楼-- · 2020-08-01 05:37

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 bytes for data storage, all you need is to make sure that you treat them as unsigned when converting values to bytes (use explicit cast with (byte), point 1) and from bytes (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();
}
查看更多
倾城 Initia
3楼-- · 2020-08-01 05:50

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.

查看更多
▲ chillily
4楼-- · 2020-08-01 05:50

Look at Apache Commons Codec library, method DigestUtils.sha(String data). It may be useful for you.

查看更多
登录 后发表回答