domingo, 1 de febrero de 2009

Función resumen (hash) en Java

Esta es una pequeña clase que escribí para calcular el hash a un fichero mediante la función md5 los objetivos que tenía en ese momento eran dos, comparar la integridad de un fichero enviado por la red y compara dos ficheros, sin dudad el uso de esta función me facilito mucho el trabajo, espero que ustedes también, aquí les deja la clase que implemente para darle solución a este problema en JAVA.

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;

/**
*
* @author DJ_Bryan
*
*/
public class CodigoHash
{
public static String getCodigoHash(String path)
throws NoSuchAlgorithmException, FileNotFoundException, IOException
{
MessageDigest digest = MessageDigest.getInstance("MD5");
File f = new File(path);
InputStream is = new FileInputStream(f);
byte[] buffer = new byte[(int) f.length()];
int read = 0;
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);
is.close();
return output;
}
public static boolean Comparar(String file, String hashCode)
throws NoSuchAlgorithmException, FileNotFoundException, IOException
{
return hashCode.equals(getCodigoHash(file));
}
public static boolean comparar(String file1, String file2) throws NoSuchAlgorithmException, FileNotFoundException, IOException
{
return getCodigoHash(file1).equals(getCodigoHash(file2));
}
}

2 comentarios:

  1. Funciona perfecto. muchas gracias!

    ResponderEliminar
  2. Muchísimas gracias, me has salvado de un apuro en un trabajo!

    ResponderEliminar