I am creating MD5 digest in Java which is needed to calculate 4-byte hex hash of the input string. Following is the code in Java:
public static String hashString(String s) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(s.getBytes("US-ASCII"));
byte[] output = new byte[digest.length / 4];
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < digest.length; j += 4) {
System.out.print(digest[j]);
output[i] ^= digest[i + j];
}
}
return getHexString(output);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
return null;
}
}
I wanted to use the same code in Golang, however, the MD5 output is different than what I am getting in Java. Below is the code in Go:
func hashString(s string) string {
md := md5.New()
md.Write([]byte(s))
data := md.Sum(nil)
fmt.Println(data)
output := make([]byte, len(data)/4)
for i := 0; i < len(output); i++ {
for j:=0 ;j < len(data); j++ {
output[i] ^= data[i + j]
fmt.Print(output[i])
}
}
return getHexString(output)
}
I have added print statements in both code samples. As I am new in Go, I am not aware if there are any other libraries or way available to do so. I just followed what I found on internet. It would be really great if someone can help with this.