I'd like to get the same hash value in java as the md5sum/opensl command.
I can't get the result I expected.
How do I write in java to get the same result?
(1) For the md5sum/opensl command
$echoabc|md5sum
0bee89b07a248e27c83fc3d5951213c1-
$ echoabc | openssl md5
(stdin) = 0bee89b07a248e27c83fc3d5951213c1
$
(2) For java programs (Apache Common Codec, MessageDigest)
·Source
package test;
import java.math.BigInteger;
import java.security.MessageDigest;
import org.apache.commons.codec.digest.DigestUtils;
public class Md5sum2 {
public static void main(String[]args) {
String str = "abc";
// 1. MessageDiget
try{
byte [ ] input = str.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5 = md.digest(input);
BigInteger bigInt = new BigInteger(1,md5);
String result = bigInt.toString(16);
System.out.println("result:"+result);
} catch(Exceptionex){
ex.printStackTrace();
through new RuntimeException (ex);
}
// 2. Apache Commons Codec
String out = DigestUtils.md5Hex(str);
System.out.println("result:"+out);
}
}
·Results of execution
$java-cp to /.m2/repository/commons-codec/commons-codec/1.10/commons-codec-1.10.jar:.test.Md5sum2
result —900150983cd24fb0d6963f7d28e17f72
result —900150983cd24fb0d6963f7d28e17f72
$
echo
automatically adds a new line when there is no new line at the end of the string.
So echoabc|md5sum
is actually calculating the MD5 hash of "abc\n"
.
In Java,
String str="abc\n";
You can get the same results as echoabc|md5sum
.
Conversely, if you want echoabc|md5sum
to get the same result as Java, you can add the echo
option to echo
to calculate the MD5 hash of the "abc"
itself because no new line is added.
$echo-nabc | md5sum
900150983cd24fb0d6963f7d28e17f72-
© 2024 OneMinuteCode. All rights reserved.