我想計算一個簡單的程序,它將執行一個MD5來散列我輸入的二進制值。MD5二進制字符串轉換爲字節數組
我已經試過谷歌,所有程序陳述是哈希字符串。 這不是我要找的。我想散列二進制,結果會以十六進制形式給我。
以下是我試過的代碼,但是, 在返回語句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,你真的希望它是什麼?一個二進制編碼的整數?還有別的嗎? – fvu
binary> hash> hex – moon
是的,但二進制什麼?在你的例子中是0和1代表個別位(意味着給出的是22位數)? – fvu