Java-生成文件的校验和-(SHA-1-MD5)

Java-生成文件的校验和-(SHA-1-MD5)

Tags: Java

摘要

Java-生成文件的校验和-(SHA-1-MD5)

生成文件的校验和值

package cn.javacore.io.file;

import java.io.FileInputStream;
import java.security.MessageDigest;

public class _27_TestCheckSum {

    public static void main(String args[]) throws Exception {

        String datafile = "/home/zhu/javacore.cn/file.txt";

        MessageDigest md = MessageDigest.getInstance("SHA1");
        FileInputStream fis = new FileInputStream(datafile);
        byte[] dataBytes = new byte[1024];

        int nread = 0;

        while ((nread = fis.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        }

        byte[] mdbytes = md.digest();

        //转换字节为16进制格式,方便显示
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }

        System.out.println("Digest(in hex format):: " + sb.toString());

    }
}

输出

Digest(in hex format):: 69bab01e3c35c55aa138e5d4a70511c7983d66cd

如果把MessageDigest md = MessageDigest.getInstance("SHA1");
改为MessageDigest md = MessageDigest.getInstance("MD5");
输出结果为

Digest(in hex format):: 3983534dc4902be492b70173a93bd898

SHA1和MD5是两种用的最多的消息摘要算法。