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 HashFile {
private File file;
private String Algoritmo;
public HashFile(String filename,String Algoritmo){
this.file = new File(filename);
this.Algoritmo = Algoritmo;
}
public String HashFileGenera() {
String output;
try{
MessageDigest digest = MessageDigest.getInstance(this.Algoritmo);
InputStream is = new FileInputStream(file);
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);
output = bigInt.toString(16);
// System.out.println("MD5: " + output);
return output;
}
catch(IOException e) {
throw new RuntimeException("Unable to process file for "+this.Algoritmo, e);
}
finally {
try {
is.close();
}
catch(IOException e) {
throw new RuntimeException("Unable to close input stream for "+this.Algoritmo+" calculation", e);
}
}
}catch(NoSuchAlgorithmException | FileNotFoundException e){
e.printStackTrace();
}
return Algoritmo;
}
public String toString(){
return (
"" + this.Algoritmo + " : " + this.HashFileGenera()
);
}
public boolean equals(Object o){
HashFile p = (HashFile) o;
return ( this.HashFileGenera().equals(p.HashFileGenera())
);
}
}