]> matita.cs.unibo.it Git - logicplayer.git/blob - server/com/company/MD5.java
623f11f280bf954de286e7ca233bfc332935bdaa
[logicplayer.git] / server / com / company / MD5.java
1 package com.company;
2
3 import java.io.FileInputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.security.MessageDigest;
7 import java.security.NoSuchAlgorithmException;
8
9
10 public class MD5 {
11
12     MD5(){}
13     public static String digest(String filePath) {
14         InputStream inputStream = null;
15         try {
16             inputStream = new FileInputStream(global.locationEsercizi+filePath);
17             byte[] buffer = new byte[1024];
18             MessageDigest digest = MessageDigest.getInstance("MD5");
19             int numRead = 0;
20             while (numRead != -1) {
21                 numRead = inputStream.read(buffer);
22                 if (numRead > 0)
23                     digest.update(buffer, 0, numRead);
24             }
25             byte [] md5Bytes = digest.digest();
26             System.out.println(convertHashToString(md5Bytes));
27             return convertHashToString(md5Bytes);
28         } catch (Exception e) {
29             return null;
30         } finally {
31             if (inputStream != null) {
32                 try {
33                     inputStream.close();
34                 } catch (Exception e) { }
35             }
36         }
37     }
38
39     private static String convertHashToString(byte[] md5Bytes) {
40         String returnVal = "";
41         for (int i = 0; i < md5Bytes.length; i++) {
42             returnVal += Integer.toString(( md5Bytes[i] & 0xff ) + 0x100, 16).substring(1);
43         }
44         return returnVal;
45     }
46 }