/* 
 * Diplomová práce ÚSI VUT 
 * Forenzní analýza webového prohlížeče
 *
 * Autor: Michal Bača
 * Datum: 20.5.2015
 */
package yafft.Utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.DatatypeConverter;

/**
 *
 * @author michal
 */
public class Hash {

    private static String getCheckSum(Path p, HashAlgoritms a, Boolean verbose) {
        if (p.toFile().isFile()) {

            try {
                //System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXX " + a.toString());
                MessageDigest md = MessageDigest.getInstance(a.toString());
                md.update(Files.readAllBytes(p));

                byte[] digest = md.digest();

                String checkSum = DatatypeConverter.printHexBinary(digest);
                if (verbose) {
                    System.out.println(md.getAlgorithm() + "\t" + checkSum);
                }
                //System.out.println(checkSum);

                return checkSum;

            } catch (NoSuchAlgorithmException | IOException ex) {
                Logger.getLogger(Hash.class.getName()).log(Level.SEVERE, null, ex);
            }

            return "";

        }

        return "";
    }

    /**
     *
     * @param p
     * @return
     */
    public static String getMD5(Path p) {
        return getCheckSum(p, HashAlgoritms.MD5, false);

    }

    public static String getSHA256(Path p) {
        return getCheckSum(p, HashAlgoritms.SHA256, false);
    }

    public static String getMD5(Path p, Boolean verbose) {
        return getCheckSum(p, HashAlgoritms.MD5, verbose);

    }

    public static String getSHA256(Path p, Boolean verbose) {
        return getCheckSum(p, HashAlgoritms.SHA256, verbose);
    }

    public Boolean isEqual(String checkSum1, String checkSum2) {

        return MessageDigest.isEqual(checkSum1.getBytes(), checkSum2.getBytes());

    }

}
