android对文件的MD5验证

来源:互联网 发布:淘宝客招代理文案 编辑:程序博客网 时间:2024/05/16 12:57
  1. import java.security.MessageDigest;  
  2. import java.io.FileInputStream;  
  3. import java.io.InputStream;  
  4.   
  5. public class MD5 {  
  6.     private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
  7. 'A', 'B', 'C', 'D', 'E', 'F' };  
  8.   
  9.     public static void main(String[] args)  
  10.     {  
  11.         System.out.println(md5sum("/init.rc"));  
  12.     }  
  13.   
  14.     public static String toHexString(byte[] b) {  
  15.         StringBuilder sb = new StringBuilder(b.length * 2);  
  16.         for (int i = 0; i < b.length; i++) {  
  17.             sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);  
  18.             sb.append(HEX_DIGITS[b[i] & 0x0f]);  
  19.         }  
  20.         return sb.toString();  
  21.     }  
  22.   
  23.     public static String md5sum(String filename) {  
  24.         InputStream fis;  
  25.         byte[] buffer = new byte[1024];  
  26.         int numRead = 0;  
  27.         MessageDigest md5;  
  28.         try{  
  29.             fis = new FileInputStream(filename);  
  30.             md5 = MessageDigest.getInstance("MD5");  
  31.             while((numRead=fis.read(buffer)) > 0) {  
  32.                 md5.update(buffer,0,numRead);  
  33.             }  
  34.             fis.close();  
  35.             return toHexString(md5.digest());     
  36.         } catch (Exception e) {  
  37.             System.out.println("error");  
  38.             return null;  
  39.         }  
  40.     }  

0 0