com.soento.core.util.Md5Util Maven / Gradle / Ivy
package com.soento.core.util;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
/**
* @author yantao.zeng
*/
public final class Md5Util {
public static String encode(String input, Charset charset) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(input.getBytes(charset));
return HexUtil.bytes2Hex(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encode(String input) {
return encode(input, StandardCharsets.UTF_8);
}
public static boolean check(String input, Charset charset, String md5) {
return encode(input, charset).equalsIgnoreCase(md5);
}
public static boolean check(String input, String md5) {
return check(input, StandardCharsets.UTF_8, md5);
}
public static String encode(File file) {
InputStream in = null;
try {
in = new FileInputStream(file);
return DigestUtils.md5Hex(in);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
StreamUtil.close(in);
}
}
public static boolean check(File file, String md5) {
return encode(file).equalsIgnoreCase(md5);
}
}