Java 中是否有用于哈希的 hexToString 实现方法?
我正在使用一种对字符串进行哈希处理的小方法。寻找信息,我发现 MessageDigest 可以帮助我完成这个任务,在这里
但现在我有一个问题。看来在 Java 中对字符串进行哈希处理的过程总是相同的:
- 创建 MessageDigester 并指定要使用的算法。
- 您使用要散列的字符串更新 MessageDigester
- 然后调用 MessageDigester.digest 并获得一个 byte[]。
如果哈希最常用的功能之一是获取该哈希的字符串版本,为什么(在我提到的问题和其他一些问题中)人们必须实现他们的 convToHex 方法?
private static String convToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
是否有 Java 方法允许我在 MessageDigester 返回的 byte[] 和 String 之间进行解析?如果存在的话,它在哪里??如果不是,为什么我必须制定自己的方法?
谢谢。
I'm working in a little method that hashes a String. Looking for information, I could find that MessageDigest can help me to make this task, here
But now I have a question. It seems that the procedure to hash a String in Java it's always the same:
- You create your MessageDigester and specify the algorithm to use.
- You updates the MessageDigester with the String to hash
- Then you call MessageDigester.digest and you get a byte[].
If one of the most used fonctionnalities of a hash it's to get the String version of this hash, why (in the question I refered and some other) people have to implement their convToHex method?
private static String convToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
Is there a Java method that allows me to make this parse between the byte[] returned by the MessageDigester and a String?? If it exists, where is it?? If not, why do I have to make my own method?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用具有
Hex
类的 Commons Codec 。除此之外,如果您不想包含另一个依赖项,您可以将转换写得更短:(我知道,我知道,循环中的字符串连接,我拥有的字节数组具有固定的短长度。请随意更改它使用
StringBuilder
。)You could use Commons Codec which has a
Hex
class. Apart from that you can write the conversion much shorter if you don't want to include another dependency:(I know, I know, string concatenation in a loop, the byte arrays I have are of a fixed short length. Feel free to change it to use
StringBuilder
.)