]> matita.cs.unibo.it Git - logicplayer.git/blob - server/com/company/MD5.java
Updated to new version.
[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             return convertHashToString(md5Bytes);
27         } catch (Exception e) {
28             return null;
29         } finally {
30             if (inputStream != null) {
31                 try {
32                     inputStream.close();
33                 } catch (Exception e) { }
34             }
35         }
36     }
37
38     private static String convertHashToString(byte[] md5Bytes) {
39         String returnVal = "";
40         for (int i = 0; i < md5Bytes.length; i++) {
41             returnVal += Integer.toString(( md5Bytes[i] & 0xff ) + 0x100, 16).substring(1);
42         }
43         return returnVal;
44     }
45 }