import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* md5工具
*/
public class Md5Util {
private static final char hexDigits[] ={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 计算字符串的md5串
*/
public static byte[] md5( String str ){
try {
return md5( str.getBytes( "utf-8" ) );
} catch (UnsupportedEncodingException e) {
throw new RuntimeException( e );
}
}
/**
* 计算文件的md5串
*/
public static byte[] md5( File file ){
byte[] bytes = new byte[ (int)file.length() ];
try {
FileInputStream fis = new FileInputStream( file );
fis.read( bytes );
fis.close();
} catch (IOException e) {
throw new RuntimeException( e );
}
return md5( bytes );
}
/**
* 计算字节数组的md5串
*/
public static byte[] md5( byte[] bytes ){
try {
MessageDigest messageDigest = MessageDigest.getInstance( "MD5" );
byte[] bs = messageDigest.digest( bytes );
return bs;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException( e );
}
}
public static String toHexString(byte[] bytes) {
if (bytes == null) {
return "";
}
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
hex.append(hexDigits[(b >> 4) & 0x0F]);
hex.append(hexDigits[b & 0x0F]);
}
return hex.toString();
}
/**
* 方法描述:文件加密添加解串
*/
public static String md5File(File file) throws IOException {
return toHexString( md5(file));
}
}
转载于:https://blog.51cto.com/7915791/1865951