【发布时间】:2017-03-17 22:54:40
【问题描述】:
我想计算一个简单的程序,它会在其中执行 MD5,以散列我输入的二进制值。
我试过谷歌,所有所说的程序都是散列字符串。 那不是我要找的。我想对二进制进行哈希处理,结果将以十六进制形式提供给我。
下面是我尝试过的代码,但是,
return 语句 return hash 有一个错误,它指出 byte[] 不能转换为字符串。
有人可以帮我解决这个问题吗?您的帮助将不胜感激。 我是编程密码算法的新手。
import java.security.*;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class JavaApplication1 {
public static String getMD5(byte[] plaintext) throws Exception{
//init hash algorithm
MessageDigest md = MessageDigest.getInstance("MD5");
//compute hash
byte[] hash = md.digest(plaintext);
//display hash in hex
System.out.println(tohex(hash));
return hash;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println(getMD5(0111001101101000011001));
}
public static String tohex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
【问题讨论】:
-
由于
0111001101101000011001在Java 中没有任何合法性,您真正希望它是什么?以二进制编码的整数?还有什么? -
二进制 > 哈希 > 十六进制
-
是的,但是二进制什么?您的示例中的 0 和 1 是否代表单个位(意味着给出的是 22 位数字)?
-
@fvu 我发布的二进制值只是二进制值的一个例子