关于MD5文件的校验

来源:互联网 发布:网站域名后缀 编辑:程序博客网 时间:2024/04/30 19:28

        首先MD5文件的校验的作用是执行散列运算来检查数据的正确性。我们用的最多的就是对数据传输完成后对文件的检验。

        MD5的生成

import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.math.BigInteger;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/** *  根据文件生成md5密串 */public class MD5File {    protected static long SINGLE_CHECK = 10*1024*1024;        protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };    protected static MessageDigest messagedigest = null;    static {        try {            messagedigest = MessageDigest.getInstance("MD5");        } catch (NoSuchAlgorithmException nsaex) {            System.err.println(MD5File.class.getName()                    + "初始化失败,MessageDigest不支持MD5Util。");            nsaex.printStackTrace();        }    }    /**     * create MD5 string from file     *      * @param file     * @return     * @throws IOException     */    public static String getFileMD5String(File file) throws IOException {                if(UserApplication.getApplication().getDownloadType().mSetupDownload.equalsIgnoreCase("true"))        {            return getFileMD5(file);        }        else         {                FileInputStream in = new FileInputStream(file);            FileChannel ch = in.getChannel();            long total = file.length();            long current = 0;            long last = total % SINGLE_CHECK;            long count = total / SINGLE_CHECK;            StringBuilder builder = new StringBuilder();            try {                for (long i = 0; i < count; i++) {                    String MD5Cache = getMD5String(ch, i * SINGLE_CHECK,                            SINGLE_CHECK);                                        builder.append(MD5Cache);                    current++;                }                if (last != 0) {                    String MD5Cache = getMD5String(ch, count * SINGLE_CHECK, last);                                        builder.append(MD5Cache);                }            } finally {                if (ch != null) {                    try {                        ch.close();                    } catch (IOException e) {                        // nothing                    } finally {                        ch = null;                    }                }                    if (in != null) {                    try {                        in.close();                    } catch (IOException e) {                        // nothing                    } finally {                        in = null;                    }                }            }            return builder.toString();        }    }        private static String getFileMD5(File file)     {        if (!file.isFile())        {          return null;        }        MessageDigest digest = null;        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)          {              digest.update(buffer, 0, len);          }                    in.close();        } catch (Exception e) {          e.printStackTrace();          return null;        }        return bufferToHex(digest.digest());    }        private static String getMD5String(FileChannel ch, long pos, long size)            throws IOException {        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY,                pos, size);        messagedigest.update(byteBuffer);        return bufferToHex(messagedigest.digest());    }    /**     * create MD5 string from string     * @param s     * @return     */    public static String getMD5String(String s) {        return getMD5String(s.getBytes());    }        /**     * create MD5 string from byte array     * @param bytes     * @return     */    public static String getMD5String(byte[] bytes) {        messagedigest.update(bytes);        return bufferToHex(messagedigest.digest());    }    private static String bufferToHex(byte bytes[]) {        return bufferToHex(bytes, 0, bytes.length);    }    private static String bufferToHex(byte bytes[], int m, int n) {        StringBuffer stringbuffer = new StringBuffer(2 * n);        int k = m + n;        for (int l = m; l < k; l++) {            appendHexPair(bytes[l], stringbuffer);        }        return stringbuffer.toString();    }    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {        char c0 = hexDigits[(bt & 0xf0) >> 4];        char c1 = hexDigits[bt & 0xf];        stringbuffer.append(c0);        stringbuffer.append(c1);    }        private MD5File(){}}


对文件完整性进行校验,必然会对全文数据的获取。上面是个工具类可以获取到某个文件的MD5

            

0 0
原创粉丝点击