SHA-1 哈希值与字符串混合
我必须解析类似以下内容的“某些文本 <40 字节哈希>” 我可以将整个内容读入字符串而不损坏 40 字节哈希部分吗?
问题是哈希不会在那里,所以我不想在阅读时处理它。
编辑:我忘了提及 40 字节哈希是 2x20 字节哈希,没有编码原始字节。
I have to parse something like the following "some text <40 byte hash>" can i read this whole thing in to a string without corrupting 40 byte hash part?
The thing is hash is not going to be there so i don't want to process it while reading.
EDIT: I forgot to mention that the 40 byte hash is 2x20 byte hashes no encoding raw bytes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
工作代码:
将字节字符串输入转换为十六进制字符,这在几乎所有字符串编码中都是安全的。 使用我在其他问题中发布的代码将十六进制字符解码回原始字节。
WORKING CODE:
Converts byte string inputs into hex characters which should be safe in almost all string encodings. Use the code I posted in your other question to decode the hex chars back to raw bytes.
好的,既然您已经澄清了这些是原始字节,
不,您不能将其作为字符串读入 Java,您需要将其作为原始字节读取。
OK, now that you've clarified that these are raw bytes
No, you cannot read this into Java as a string, you will need to read it as raw bytes.
更多细节可能会有用,但我认为答案是你应该没问题。
您没有说明 SHA-1 哈希值是如何编码的(常见的可能性包括“无”(原始字节)、Base64 和十六进制)。 由于 SHA-1 生成 20 字节(160 位)散列,我猜测它将使用十六进制进行编码,因为这会使您提到的 40 字节所需的空间增加一倍。 通过这种编码,将使用 2 个字符对哈希中的每个字节进行编码,使用符号 0 到 9 以及 A 到 F。这些都是 ASCII 字符,因此您是安全的。
Base64 编码也可以工作(尽管可能不是您所要求的,因为它增加了大约 1/3 的大小,使您的长度远远小于 40 个字节),因为 Base64 中使用的每个字符也是 ASCII。
如果直接使用原始字节,则会遇到问题,因为某些值不是有效字符。
Some more details could be useful, but I think the answer is that you should be okay.
You didn't say how the SHA-1 hash was encoded (common possibilities include "none" (the raw bytes), Base64 and hex). Since SHA-1 produces a 20 byte (160 bit) hash, I am guessing that it will be encoded using hex, since that doubles the space needed to the 40 bytes you mentioned. With that encoding, 2 characters will be used to encode each byte from the hash, using the symbols 0 through 9 and A through F. Those are all ASCII characters so you are safe.
Base64 encoding would also work (though probably not what you asked about since it increases the size by about 1/3 leaving you at well less than 40 bytes) as each of the characters used in Base64 are also ASCII.
If the raw bytes were used directly, you would have a problem, as some of the values are not valid characters.
SHA-1 哈希值的长度为 20 字节(160 位)。 如果您正在处理 40 个字符的哈希值,那么它们可能是哈希值的 ASCII 表示形式,因此仅包含字符 0-9 和 af。 如果是这种情况,那么您应该能够毫无问题地读取和操作 Java 中的字符串。
SHA-1 hashes are 20 bytes (160 bits) in length. If you are dealing with 40 character hashes, then they are probably an ASCII representation of the hash, and therefore only contain the characters 0-9 and a-f. If this is the case, then you should be able to read and manipulate the strings in Java without any trouble.
从输入流中将其作为字节流读取,然后将字符串从流中剥离出来,如下所示:
然后获取字节:
Read it from your input stream as a byte stream, and then strip the String out of the stream like this:
Then get your bytes as: