java中可以用两种方法实现,我们先说麻烦一点的,代码:
public class md5_test { //md5的字符串常量 private final static string[] hexdigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public static void main(string[] args) { // todo auto-generated method stub try { messagedigest messagedigest= messagedigest.getinstance("md5"); system.out.println(bytearraytohexstring(messagedigest.digest("baidu.com".getbytes()))); } catch (nosuchalgorithmexception e) { // todo auto-generated catch block e.printstacktrace(); } } private static string bytearraytohexstring(byte[] b) { stringbuffer resultsb = new stringbuffer(); for (int i = 0; i < b.length; i++) { resultsb.append(bytetohexstring(b[i])); } return resultsb.tostring(); } /** 将一个字节转化成十六进制形式的字符串 */ private static string bytetohexstring(byte b) { int n = b; if (n < 0) n = 256 + n; int d1 = n / 16; int d2 = n % 16; return hexdigits[d1] + hexdigits[d2]; } }
下面是简单的,但是需要导入一个jar包:commons-codec,
比如我用的这个commons-codec-1.4.jar代码:
import org.apache.commons.codec.digest.digestutils; public class tomain { public static void main(string[] args) { system.out.println(digestutils.md5hex("baidu.com")); } }
更多使用java获取md5值的两种方法。
