您的位置:首页 > 其它

MD5加密(字符串、文件)工具类,直接用!!!

2016-04-06 16:31 507 查看
public static String getFileMD5(File file) {
if (!file.isFile()) {
return null;
}
MessageDigest digest;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}

}
catch (Exception e) {
e.printStackTrace();
return null;
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

BigInteger bigint = new BigInteger(1, digest.digest());
StringBuilder md5 = new StringBuilder(bigint.toString(16));

return md5.toString();
}

public static String MD5(String sourceStr) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(sourceStr.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
result = buf.toString();
}
catch (NoSuchAlgorithmException e) {
System.out.println(e);
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: