mardi 26 mai 2009

java : calculer une somme MD5

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5Sample {

/**
* @param args
*/
public static void main(String[] args) {
String algo = "MD5";
System.out.println("calcul du " + algo);
BufferedReader reader =null;
try
{
reader = new BufferedReader(new FileReader("C:/temp/FFT_21117.JPG"));
char [] buffer = new char[4096];
int lus = 0;
StringBuffer stringBuffer = new StringBuffer();

// lecture fichier
while((lus = reader.read(buffer, 0, buffer.length))!=-1)
{
stringBuffer.append(buffer,0,lus);
}

// calcul MD5
byte [] hash = MessageDigest.getInstance(algo).digest(stringBuffer.toString().getBytes());

// convertion de la chaine
StringBuffer hashString = new StringBuffer();
String hex = null;

for(int i = 0; i < hash.length; i++)
{
hex = Integer.toHexString(hash[i]);
if (hex.length() == 1)
{
hashString.append('0');
hashString.append(hex.charAt(hex.length() - 1));
}
else
{
hashString.append(hex.substring(hex.length() - 2));
}
}

System.out.println("calcul du " + algo + " = [" + hashString.toString() + "]");

} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
finally
{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("fin");
}
}

Aucun commentaire:

Enregistrer un commentaire