import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5 {
// 计算文件MD5值
public static String getMD5Data(File file) {
if (!file.exists()) {
return null;
}
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length = 0;
FileInputStream fis = new FileInputStream(file);
while ((length = fis.read(buffer, 0, buffer.length)) != -1) {
md5.update(buffer, 0, length);
}
fis.close();
return byte2hex(md5.digest()).toLowerCase();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 计算字符串MD5值
public static String getMD5Data(String content) {
try {
byte []src = content.getBytes();
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(src);
return byte2hex(md5.digest()).toLowerCase();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String byte2hex(byte[] b) {
String hs = "";
String temp = "";
for (int n = 0; n < b.length; n++) {
temp = Integer.toHexString(b[n] & 0XFF);
if (temp.length() == 1) {
hs = hs + "0" + temp;
} else {
hs = hs + temp;
}
}
return hs.toUpperCase();
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5 {
// 计算文件MD5值
public static String getMD5Data(File file) {
if (!file.exists()) {
return null;
}
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length = 0;
FileInputStream fis = new FileInputStream(file);
while ((length = fis.read(buffer, 0, buffer.length)) != -1) {
md5.update(buffer, 0, length);
}
fis.close();
return byte2hex(md5.digest()).toLowerCase();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 计算字符串MD5值
public static String getMD5Data(String content) {
try {
byte []src = content.getBytes();
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(src);
return byte2hex(md5.digest()).toLowerCase();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String byte2hex(byte[] b) {
String hs = "";
String temp = "";
for (int n = 0; n < b.length; n++) {
temp = Integer.toHexString(b[n] & 0XFF);
if (temp.length() == 1) {
hs = hs + "0" + temp;
} else {
hs = hs + temp;
}
}
return hs.toUpperCase();
}
}