Home > File > Sinh giá trị Checksum của File trong Java

Sinh giá trị Checksum của File trong Java

Ví dụ sau minh họa cách sinh giá trị Checksum theo thuật toán SHA-1 cho 1 File.

package quyetdv.java.javaio.file;
import java.io.FileInputStream;
import java.security.MessageDigest;
public class GenerateCheckSum {
    public static void main(String[] args) throws Exception {
        String dataFile = "D:\\test.txt";
        MessageDigest md = MessageDigest.getInstance("SHA1");/* SHA1, MD5, ... */
        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();
        // convert the byte to hex format
        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());

Kết quả :

Digest (in hex format) :: 14119c1f91011f31771a418f1301f118f1661721a91e310115014c1d31f1

Để tìm hiểu về các thuật toán mã hóa, bạn có thể xem thêm tại : http://docs.oracle.com/javase/1.4.2/docs/guide/security/CryptoSpec.html#AppA

Categories: File
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: