Android中md5校验文件

 

在开发中,经常会需要检验传输完的文件是不是正确的文件。可以采用许多种方法,这里说下MD5检验。

下面的这个函数是进行md5检验的函数,两个参数分别表示文件下载路径,和正确的文件MD5值。

1. 得到文件的MD5值并比较与原来的MD5值是否一样

public static boolean verifyInstallPackage(String packagePath,String crc) {    
         try {
         MessageDigest sig = MessageDigest.getInstance(“MD5”);
            File packageFile = new File(packagePath);
            InputStream signedData = new FileInputStream(packageFile);
            byte[] buffer = new byte[4096];
            long toRead = packageFile.length();
            long soFar = 0;
            boolean interrupted = false;
            while (soFar < toRead) {
              interrupted = Thread.interrupted();
            if (interrupted) break;
             int read = signedData.read(buffer);
                soFar += read;
                sig.update(buffer, 0, read);
            }
            byte[] digest = sig.digest();
            String digestStr = bytesToHexString(digest);//将得到的MD5值进行移位转换
            digestStr = digestStr.toLowerCase();
            crc = crc.toLowerCase();
            if (digestStr.equals(crc)) {//比较两个文件的MD5值,如果一样则返回true
                return true;
            }
  
 } catch (Exception e) {
  // TODO: handle exception
  return false;
 }
       return false;
   }

2 bytesToHexString MD5值移位转换

public static String bytesToHexString(byte[] src) {
       StringBuilder stringBuilder = new StringBuilder(“”);
       if (src == null || src.length <= 0) {
           return null;
       }
       int i = 0;
       while (i < src.length) {
           int v;
           String hv;
           v = (src[i] >> 4) & 0x0F;
           hv = Integer.toHexString(v);
           stringBuilder.append(hv);

           v = src[i] & 0x0F;
           hv = Integer.toHexString(v);
           stringBuilder.append(hv);
           i++;
       }
       return stringBuilder.toString();
   }

 

发表评论

你必须 登录后 才能对文章进行评论!

Design By Inzaghi | 京ICP备16047555号-1