]> matita.cs.unibo.it Git - logicplayer.git/blob - mainActivity/src/com/example/furt/myapplication/MD5.java
8f7bdc00dc54e323d6c9f6c52c042ae55ee82747
[logicplayer.git] / mainActivity / src / com / example / furt / myapplication / MD5.java
1 package com.example.furt.myapplication;
2
3 import android.os.Environment;
4
5 import java.io.FileInputStream;
6 import java.io.InputStream;
7 import java.security.MessageDigest;
8
9
10 public class MD5 {
11
12     MD5(){}
13
14     /*public static String digest(String fileName) throws NoSuchAlgorithmException, IOException
15     {
16
17         MessageDigest md = MessageDigest.getInstance("MD5");
18         return getDigest(new FileInputStream("/var/www/html/esercizi/"+fileName), md, 2048);
19     }
20
21     public static String getDigest(InputStream is, MessageDigest md, int byteArraySize) throws NoSuchAlgorithmException, IOException
22     {
23         md.reset();
24         byte[] bytes = new byte[byteArraySize];
25         int numBytes;
26         while ((numBytes = is.read(bytes)) != -1) {
27             md.update(bytes, 0, numBytes);
28         }
29         byte[] digest = md.digest();
30         String result = new String(Hex.encodeHex(digest));
31         return result;
32     }*/
33     public static String digest(String filePath) {
34         InputStream inputStream = null;
35         try {
36             inputStream = new FileInputStream(Environment.getExternalStorageDirectory()+"/tesiEs/"+filePath);
37             byte[] buffer = new byte[1024];
38             MessageDigest digest = MessageDigest.getInstance("MD5");
39             int numRead = 0;
40             while (numRead != -1) {
41                 numRead = inputStream.read(buffer);
42                 if (numRead > 0)
43                     digest.update(buffer, 0, numRead);
44             }
45             byte [] md5Bytes = digest.digest();
46             return convertHashToString(md5Bytes);
47         } catch (Exception e) {
48             return null;
49         } finally {
50             if (inputStream != null) {
51                 try {
52                     inputStream.close();
53                 } catch (Exception e) { }
54             }
55         }
56     }
57
58     private static String convertHashToString(byte[] md5Bytes) {
59         String returnVal = "";
60         for (int i = 0; i < md5Bytes.length; i++) {
61             returnVal += Integer.toString(( md5Bytes[i] & 0xff ) + 0x100, 16).substring(1);
62         }
63         return returnVal;
64     }
65 }