Gerar hash de arquivo

8 respostas
C

Olá pessoal, sou novo aqui no fórum e tbm no mundo Java… hehehe
Vim atrás de uma ajuda de vcs…
Preciso saber como faço para gerar o hash de um arquivo qualquer (jpg, txt, doc, ppt, etc)… Pois tenho apenas o diretório deste arquivo, onde este diretório está em um JTextField… A partir DESTE DIRETÓRIO é que preciso gerar o hash do arquivo, não do diretório em si, e sim todo conteúdo do arquivo, de modo que qualquer alteração seja detectada pelo MD5…
Segue um trecho do código abaixo…

public void actionPerformed(ActionEvent e) 
{
   	if (e.getSource() == button1)
    {	
		JFileChooser arq1 = new JFileChooser();

		// seleciona qualquer tipo de arquivo
		arq1.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
					
		int caminho1 = arq1.showOpenDialog(null);
	
		if(caminho1 == JFileChooser.APPROVE_OPTION)
		{
			File arquivo1 = arq1.getSelectedFile();
			text1.setText(arquivo1.getAbsolutePath()); //seta text1 com o diretório
                                                
             //Bem aqui preciso chamar a função MD5, passando este diretório/endereço... é possível?
		}
		else
			JOptionPane.showMessageDialog(null, "Você não selecionou nenhum diretório.");
    }	        
    else if (e.getSource() == button2)
    {
          //mesma coisa do button1
          //Jtextfield pega o endereço do arquivo2... 
    }
}

8 Respostas

M
public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException {
	MessageDigest digest = MessageDigest.getInstance("MD5");
	File f = new File("c:\\myfile.txt");
	InputStream is = new FileInputStream(f);				
	byte[] buffer = new byte[8192];
	int read = 0;
	try {
		while( (read = is.read(buffer)) > 0) {
			digest.update(buffer, 0, read);
		}		
		byte[] md5sum = digest.digest();
		BigInteger bigInt = new BigInteger(1, md5sum);
		String output = bigInt.toString(16);
		System.out.println("MD5: " + output);
	}
	catch(IOException e) {
		throw new RuntimeException("Unable to process file for MD5", e);
	}
	finally {
		try {
			is.close();
		}
		catch(IOException e) {
			throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
		}
	}		
}

é o primeiro link… [google]md5 java file[/google]

C

Vlw Mario… agora uma dúvida…
Suponha que eu coloque este código que vc postou, em uma outra classe, num arquivo diferente, com a classe chamada GeraHash, por exemplo…
Então preciso chamar essa classe GeraHash passando como parâmetro o “endereço” do arquivo, e recebendo como retorno o hash gerado…
Faço isso:

GeraHash(arquivo1.getAbsolutePath());

??? correto a chamada da classe com o endereço do arquivo como parâmetro?
e o retorno?
Desde já agradeço…

M

Melhor usar uma solução mais orientada a objetos:

File arquivo = new File ("c:/teste.txt");

geraHash(arquivo);
o código da geraHash ficaria assim:
public static String geraHash(File f) throws NoSuchAlgorithmException, FileNotFoundException{
		MessageDigest digest = MessageDigest.getInstance("MD5");
		InputStream is = new FileInputStream(f);				
		byte[] buffer = new byte[8192];
		int read = 0;
		String output = null;
		try {
			while( (read = is.read(buffer)) > 0) {
				digest.update(buffer, 0, read);
			}		
			byte[] md5sum = digest.digest();
			BigInteger bigInt = new BigInteger(1, md5sum);
			output = bigInt.toString(16);
			System.out.println("MD5: " + output);
		}
		catch(IOException e) {
			throw new RuntimeException("Não foi possivel processar o arquivo.", e);
		}
		finally {
			try {
				is.close();
			}
			catch(IOException e) {
				throw new RuntimeException("Não foi possivel fechar o arquivo", e);
			}
		}	
		
		return output;

	}

o retorno é uma String com o código MD5.

[]'s

C

Vlw Mario… vou tentar aqui… :smiley:
Brigadão mesmo…

C

E aí Mario... blz... cara... tentei aqui mas naum deu certo hein... dá o seguinte erro:
cannot find symbol method GeraHash(java.io.File)

Tenho os dois arquivos(classes) java diferentes... preciso passar o endereço do arquivo selecionado em "TelaArquivo" dentro da condição "if" para a classe(arquivo) "GeraHash"... e pegar o retorno do hash em "TelaArquivo"...
Se puder me ajudar... agradeço desde já...

Arquivo "TelaArquivo.java"
import java.awt.*; 
import java.awt.event.*;
import java.io.*;
import javax.swing.*; 

public class TelaArquivo extends JFrame
{	
	private JTextField text1
	private JButton button1
	
	public TelaArquivo()
	{	
		//.....
		//.....
		
		TrataBotao botao = new TrataBotao();    
    	button1.addActionListener(botao);     	
	}
	
	private class TrataBotao implements ActionListener, KeyListener
	{ 		
	    public void actionPerformed(ActionEvent e) 
	    {
	    	if (e.getSource() == button1)
	    	{	
				JFileChooser arq1 = new JFileChooser();

				// seleciona qualquer tipo de arquivo
				arq1.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
					
				int caminho1 = arq1.showOpenDialog(null);
	
				if(caminho1 == JFileChooser.APPROVE_OPTION)
				{
					File arquivo1 = arq1.getSelectedFile();
					text1.setText(arquivo1.getAbsolutePath());				 
  
					//Chama a classe "GeraHash.java", passando como parâmetro o endereço do arquivo
					GeraHash(arquivo1);
					
					
					//PRECISO PEGAR O "OUTPUT" AQUI!!!																				
				}
				else
					JOptionPane.showMessageDialog(null, "Você não selecionou nenhum diretório.");
	    	}	      
	    }
	    
	    public void keyPressed(KeyEvent e){	    		    	    		    	
	    }	    	    
	    public void keyReleased(KeyEvent e){
	    }	    
	    public void keyTyped(KeyEvent e){
	    }	                	    
	}
}
Arquivo "GeraHash.java"
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.swing.*;

public class GeraHash
{
	public static String GeraHash(File f) throws NoSuchAlgorithmException, FileNotFoundException
	{   
    	MessageDigest digest = MessageDigest.getInstance("MD5");   
    	InputStream is = new FileInputStream(f);                   
    	byte[] buffer = new byte[8192];   
    	int read = 0;   
    	String output = null;   
	    try 
	    {   
        	while( (read = is.read(buffer)) > 0) 
        	{   
            	digest.update(buffer, 0, read);   
        	}         
        	byte[] md5sum = digest.digest();   
        	BigInteger bigInt = new BigInteger(1, md5sum);   
        	output = bigInt.toString(16);   
        	System.out.println("MD5: " + output);   
    	}   
    	catch(IOException e) 
    	{   
        	throw new RuntimeException("Não foi possivel processar o arquivo.", e);   
    	}   
	    finally 
	    {   
        	try 
        	{   
            	is.close();   
        	}   
        	catch(IOException e) 
        	{   
            	throw new RuntimeException("Não foi possivel fechar o arquivo", e);   
        	}   
    	}     
       
    	return output;     
	} 
}

O q estou fazendo de errado??? :cry:

M

sua classe

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.security.NoSuchAlgorithmException;

import javax.swing.*;

public class TelaArquivo extends JFrame
{
	private JTextField text1;
	private JButton button1;

	public TelaArquivo()
	{
		//.....
		//.....

		TrataBotao botao = new TrataBotao();
    	button1.addActionListener(botao);
	}

	private class TrataBotao implements ActionListener, KeyListener
	{
	    public void actionPerformed(ActionEvent e)
	    {
	    	if (e.getSource() == button1)
	    	{
				JFileChooser arq1 = new JFileChooser();

				// seleciona qualquer tipo de arquivo
				arq1.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

				int caminho1 = arq1.showOpenDialog(null);

				if(caminho1 == JFileChooser.APPROVE_OPTION)
				{
					File arquivo1 = arq1.getSelectedFile();
					text1.setText(arquivo1.getAbsolutePath());
					String hash = null;


					try {
						//Chama a classe "HashMaker.java", passando como parâmetro o endereço do arquivo
						hash = HashMaker.geraHash(arquivo1);
					} catch (NoSuchAlgorithmException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}


					//PRECISO PEGAR O "OUTPUT" AQUI!!!
					//O RETORNO ESTÁ NA VARIÁVEL "hash"
				}
				else
					JOptionPane.showMessageDialog(null, "Você não selecionou nenhum diretório.");
	    	}
	    }

	    public void keyPressed(KeyEvent e){
	    }
	    public void keyReleased(KeyEvent e){
	    }
	    public void keyTyped(KeyEvent e){
	    }
	}
}
Classe que gera o hash
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashMaker
{
	public static String geraHash(File f) throws NoSuchAlgorithmException, FileNotFoundException
	{
    	MessageDigest digest = MessageDigest.getInstance("MD5");
    	InputStream is = new FileInputStream(f);
    	byte[] buffer = new byte[8192];
    	int read = 0;
    	String output = null;
	    try
	    {
        	while( (read = is.read(buffer)) > 0)
        	{
            	digest.update(buffer, 0, read);
        	}
        	byte[] md5sum = digest.digest();
        	BigInteger bigInt = new BigInteger(1, md5sum);
        	output = bigInt.toString(16);
        	System.out.println("MD5: " + output);
    	}
    	catch(IOException e)
    	{
        	throw new RuntimeException("Não foi possivel processar o arquivo.", e);
    	}
	    finally
	    {
        	try
        	{
            	is.close();
        	}
        	catch(IOException e)
        	{
            	throw new RuntimeException("Não foi possivel fechar o arquivo", e);
        	}
    	}

    	return output;
	}
}

vc tava chamando o geraHash como se ele fosse um método da classe TelaArquivo, mas ele estava em uma classe separada.
Também alterei o nome da sua classe que faz o hash, pq o nome do método tava igual ao nome da classe (podia ser confundido com o construtor da classe.

[]'s

C

Vlw mesmo pela força aí Mario… vou continuar aqui nesse problema… e se tudo correr bem… VOU CONSEGUIR… \o/… :smiley:

L

Ae Mário,
Valeu pela contribuição, igualmente ao Computeiro. As vezes a dúvida de um é a mesma de outro, desta forma multiplicamos o conhecimento.
Obrigado.

Criado 26 de outubro de 2008
Ultima resposta 30 de mar. de 2009
Respostas 8
Participantes 3