Siba/src/org/dclermonte/siba/model/SibaUtils.java

93 lines
2.0 KiB
Java
Raw Normal View History

2016-06-02 23:18:20 +02:00
package org.dclermonte.siba.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.compress.utils.IOUtils;
public class SibaUtils
{
/**
*
* @param choosenFile
* @return
* @throws IOException
*/
public static String loadMD5Sum(final File choosenFile) throws IOException
{
String result = "";
if (choosenFile.exists() && (choosenFile.length() > 32))
{
FileReader fileReader = new FileReader(choosenFile);
char[] md5 = new char[32];
byte[] md5byte = new byte[32];
for (int index = 0; index < 32; index++)
{
md5[index] = (char) fileReader.read();
md5byte[index] = (byte) md5[index];
result = result + md5[index];
}
fileReader.close();
}
//
//
return result;
}
/**
* This method calculate the MD5 itself.
*
* @param input
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static String md5(final File input) throws IOException, NoSuchAlgorithmException
{
String result;
StringBuilder hashString = new StringBuilder();
FileInputStream fileInputStream = null;
try
{
byte[] byteInput = new byte[(int) input.length()];
fileInputStream = new FileInputStream(input);
for (int index1 = 0; index1 < input.length(); index1++)
{
byteInput[index1] = (byte) fileInputStream.read();
}
byte[] hash = null;
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
hash = messageDigest.digest(byteInput);
for (int index = 0; index < hash.length; index++)
{
String hex = Integer.toHexString(hash[index]);
if (hex.length() == 1)
{
hashString.append('0');
hashString.append(hex.charAt(hex.length() - 1));
}
else
{
hashString.append(hex.substring(hex.length() - 2));
}
}
fileInputStream.close();
result = hashString.toString();
}
finally
{
IOUtils.closeQuietly(fileInputStream);
}
//
return result;
}
}