I would like to compute a simple program, where it will do a MD5, to hash the binary value that I've input.
I've tried google, all the program stated is hashing string. That's not I'm looking for. I want to hash binary and the result will give me in hexadecimal form.
Below is the code that I've tried, however,
there's an error over at the return statement return hash
, it state that byte[] cannot be converted to string.
can someone help me out with this? your help will greatly be appreciated. I'm new in programming crytographic algorithm.
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();
}
}