Mega Code Archive

 
Categories / Android / Security
 

Create Md5 Checksum

//package com.si.anddos.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.MessageDigest; import java.util.Date; /**  *   * @author Carlos Martinez  */ class Utils {   // --------- Carlos Martinez -------------------   public static String inputStreamAsString(InputStream stream)       throws IOException {     BufferedReader br = new BufferedReader(new InputStreamReader(stream,         "UTF-8"));     StringBuilder sb = new StringBuilder();     String line = null;     while ((line = br.readLine()) != null) {       sb.append(line).append('\n');     }     br.close();     return sb.toString();   }   // ----------- Carlos Martinez ----------------------   public static String parseLastValueStr(String s, String oddelovac) {     return s.substring(s.lastIndexOf(oddelovac) + 1);   }   public static long getDateLong() {     Date d = new Date();     return d.getTime();   }   public static String getMD5(File file) throws FileNotFoundException,       IOException {     /*      * try { MessageDigest md =      * java.security.MessageDigest.getInstance("MD5"); FileInputStream fio =      * new FileInputStream(file);      *       * int length = (int)file.length(); byte [] bytes = new byte[length];      * fio.read(bytes);      *       * md.update(bytes); md.digest(); } catch (NoSuchAlgorithmException e) {      * e.printStackTrace(); }      *       * FileInputStream fis = new FileInputStream( file ); String md5 =      * "";//org.apache.commons.codec.digest.DigestUtils.md5Hex( fis );      *       * return md5;      */     try {       return getMD5Checksum(file.getAbsolutePath());     } catch (Exception e) {       e.printStackTrace();     }          return "";   }   public static byte[] createChecksum(String filename) throws Exception {     InputStream fis = new FileInputStream(filename);     byte[] buffer = new byte[1024];     MessageDigest complete = MessageDigest.getInstance("MD5");     int numRead;     do {       numRead = fis.read(buffer);       if (numRead > 0) {         complete.update(buffer, 0, numRead);       }     } while (numRead != -1);     fis.close();     return complete.digest();   }   // see this How-to for a faster way to convert   // a byte array to a HEX string   public static String getMD5Checksum(String filename) throws Exception {     byte[] b = createChecksum(filename);     String result = "";     for (int i = 0; i < b.length; i++) {       result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);     }     return result;   } }