使用摘要流获取文件的MD5

摘要流是过滤流的一种,使用它可以再读取和写入流时获取流的摘要信息(MD5/SHA).

使用摘要流包装流时,需要额外传递一个MessageDigest对象,

MessageDigest md=MessageDigest.getInstance("MD5");
DigestInputStream dis=new DigestInputStream(in, md);

摘要流复写了流的read、write方法,方法内部调用MessageDigest对象的upate()来更新摘要信息

public int read() throws IOException {
        int ch = in.read();
        if (on && ch != -1) {
            digest.update((byte)ch);
        }
        return ch;
    }

调用MessageDigest对象的getDigest()可以获得摘要信息的byte[],通常情况我们需要获取字符串形式的MD5值,所以需要进行转换

/**
     * 将字节数组转为十六进制字符串
     * 
     * @param bytes
     * @return 返回16进制字符串
     */
    public static String byteArrayToHex(byte[] bytes) {
        // 字符数组,用来存放十六进制字符
        char[] hexReferChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        // 一个字节占8位,一个十六进制字符占4位;十六进制字符数组的长度为字节数组长度的两倍
        char[] hexChars = new char[bytes.length * 2];
        int index = 0;
        for (byte b : bytes) {
            // 取字节的高4位
            hexChars[index++] = hexReferChars[b >>> 4 & 0xf];
            // 取字节的低4位
            hexChars[index++] = hexReferChars[b & 0xf];
        }
        return new String(hexChars);
    }

 -----------------------------------------------------

2014.8.25

今天看到网上有使用BigInteger来进行byte[]和十六进制的转换:

        byte[] d=md5.digest();
        BigInteger bigInt=new BigInteger(1,d);
        System.out.println(bigInt.toString(16));

 

posted @ 2014-08-15 22:03  _流年  阅读(707)  评论(0编辑  收藏  举报