Java Digest File digestFile(String filename, String algorithm)

Here you can find the source of digestFile(String filename, String algorithm)

Description

Calculate digest of given file with given algorithm.

License

Apache License

Parameter

Parameter Description
filename the String name of the file to be hashed
algorithm the algorithm to be used to compute the digest

Declaration

public static void digestFile(String filename, String algorithm) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import javax.mail.internet.MimeUtility;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.OutputStream;
import java.security.MessageDigest;

public class Main {
    /***/*from  w w  w .  j ava2  s . co  m*/
     * Calculate digest of given file with given algorithm.
     * Writes digest to file named filename.algorithm .
     *
     * @param filename the String name of the file to be hashed
     * @param algorithm the algorithm to be used to compute the digest
     */
    public static void digestFile(String filename, String algorithm) {
        byte[] b = new byte[65536];
        int count = 0;
        int read = 0;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            fis = new FileInputStream(filename);
            while (fis.available() > 0) {
                read = fis.read(b);
                md.update(b, 0, read);
                count += read;
            }
            byte[] digest = md.digest();
            StringBuffer fileNameBuffer = new StringBuffer(128).append(filename).append(".").append(algorithm);
            fos = new FileOutputStream(fileNameBuffer.toString());
            OutputStream encodedStream = MimeUtility.encode(fos, "base64");
            encodedStream.write(digest);
            fos.flush();
        } catch (Exception e) {
            System.out.println("Error computing Digest: " + e);
        } finally {
            try {
                fis.close();
                fos.close();
            } catch (Exception ignored) {
            }
        }
    }
}

Related

  1. digestFile(File file)
  2. digestFile(File file, String algorithm)