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)); } }
MessageDigest---md5哈希算法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.