对文件生产MD5摘要

来源:互联网 发布:windows未正确加载 编辑:程序博客网 时间:2024/05/21 07:12

转载注明出处

import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.security.MessageDigest;public class Md5 {/**     * 对文件全文生成MD5摘要     *      * @param file     *            要加密的文件     * @return MD5摘要码     */    public static String getMD5(File file) {        FileInputStream fis = null;        try {            MessageDigest md = MessageDigest.getInstance("MD5");            fis = new FileInputStream(file);            byte[] buffer = new byte[2048];            int length = -1;            long s = System.currentTimeMillis();            while ((length = fis.read(buffer)) != -1) {                md.update(buffer, 0, length);            }            byte[] b = md.digest();            return bytesToHexString(b);            // 16位加密            // return buf.toString().substring(8, 24);        } catch (Exception ex) {            ex.printStackTrace();            return null;        } finally {            try {                fis.close();            } catch (IOException ex) {                ex.printStackTrace();            }        }    } /** */    /**     * 把byte[]数组转换成十六进制字符串表示形式     * @param tmp    要转换的byte[]     * @return 十六进制字符串表示形式     */    public static String bytesToHexString(byte[] src){               StringBuilder stringBuilder = new StringBuilder();               if (src == null || src.length <= 0) {                   return null;              }               for (int i = 0; i < src.length; i++) {                  int v = src[i] & 0xFF;                   String hv = Integer.toHexString(v);                           if (hv.length() < 2) {                       stringBuilder.append(0);                   }                   stringBuilder.append(hv);               }               return stringBuilder.toString();           }        public static void main(String[] args){    System.out.println(getMD5(new File("C:/Users/pc/Desktop/mobileqqandroid.apk")));    } }


0 0