Java SHA-1 对无符号字节进行哈希处理
嘿伙计们!
我有以下问题: 我需要在 Java 中对一个无符号字节进行哈希处理,该字节在 0-255 之间。 主要问题是java根本没有无符号字节类型。 我找到了一个解决方法,并使用 int 而不是 byte 并进行了一些修改。
主要问题是:Java.securitys Messagedigest.digest 函数仅接受字节数组类型,但我需要给它一个 int 数组。
有人有一个简单的解决方法吗? 我正在寻找第三方 sha-1 函数,但没有找到。也没有任何示例代码。
所以基本上我需要的是: 我有一个无符号字节值,例如:0xFF,需要获取以下 sha1 哈希值:85e53271e14006f0265921d02d4d736cdc580b0b
任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
重要的是要了解有符号字节和无符号字节在表示方面没有区别。符号性是关于算术运算如何处理字节(在 2 的补码表示的情况下,加法和减法除外)。
因此,如果您使用
byte
进行数据存储,您所需要做的就是确保在将值转换为byte
时将它们视为无符号(使用带有byte
的显式强制转换) code>(byte),第 1 点)和来自byte
(防止使用& 0xff
进行符号扩展,第 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).
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):查看Apache Commons Codec库,方法DigestUtils.sha(字符串数据)。它可能对你有用。
Look at Apache Commons Codec library, method DigestUtils.sha(String data). It may be useful for you.
摘要不会关心 Java 如何感知字节的符号;它只关心字节的位模式。试试这个:
这应该打印
85e53271e14006f0265921d02d4d736cdc580b0b
。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
.