Java SHA-1哈希未签名的BYTE [英] Java SHA-1 hash an unsigned BYTE

查看:60
本文介绍了Java SHA-1哈希未签名的BYTE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!

我有以下问题:
我需要在Java中散列一个(将是...)之间的无符号字节0-255。
主要问题是java根本没有unsigned Byte类型。
我找到了解决方法,并使用int而不是byte进行了一些修改。

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.

主要问题是:Java.securitys仅是Messagedigest.digest函数接受字节数组类型,但是我需要给它一个int数组。

The main problem is: Java.securitys Messagedigest.digest function only accepts byte array types, but i would need to give it an int array.

有人为此有一个simpe解决方法吗?
我正在寻找第三方sha-1函数,但未找到任何函数。也没有任何示例代码。

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.

所以基本上我需要什么:
我有一个无符号字节值,例如:0xFF并需要获取以下sha1哈希值:85e53271e14006f0265921d02d4d736cdc580b0b

So basically what i need: I have an unsigned byte value for example: 0xFF and need to get the following sha1 hash: 85e53271e14006f0265921d02d4d736cdc580b0b

任何帮助将不胜感激。

推荐答案

请理解,有符号和无符号字节的表示形式没有区别。符号性是关于如何通过算术运算(对于2的补码表示法,不是加法和减法)来处理字节。

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).

因此,如果使用 byte s用于数据存储,您需要做的就是确保在将值转换为 byte s时将它们视为无符号的(使用显式使用(字节),点1)和 byte s(防止使用扩展符号)进行转换& 0xff ,第2点):

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();
}

这篇关于Java SHA-1哈希未签名的BYTE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆