读书人

MD5印证器

发布时间: 2012-12-24 10:43:14 作者: rapoo

MD5验证器

import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class Digest{    /**     * 获取指定文件的md5值。     *      * @param path 待验证的文件名     */    public static String checkMD5(String path)    {        StringBuilder sb = new StringBuilder();        try        {            MessageDigest md5 = MessageDigest.getInstance("MD5");// 生成MD5类的实例            File file = new File(path); // 创建文件实例,设置路径为方法参数            FileInputStream fs = new FileInputStream(file);            BufferedInputStream bi = new BufferedInputStream(fs);            ByteArrayOutputStream bo = new ByteArrayOutputStream();            byte[] b = new byte[bi.available()]; // 定义字节数组b大小为文件的不受阻塞的可访问字节数            // int i;            // 将文件以字节方式读到数组b中            while ((bi.read(b, 0, b.length)) != -1)            {            }            md5.update(b);// 执行MD5算法            for (byte by : md5.digest())            {                sb.append(String.format("%02X", by));// 将生成的字节MD5值转换成字符串            }            bo.close();            bi.close();        }        catch (NoSuchAlgorithmException e)        {            e.printStackTrace();            return null;        }        catch (IOException e)        {            return null;        }        return sb.toString();// 返回MD5值    }    public static void main(String[] args) throws Exception    {        String md5 = checkMD5("c:\\MM.MP3");        System.out.println(md5);    }}

读书人网 >编程

热点推荐