Java tutorial
//package com.java2s; /* * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import android.util.Log; import java.io.BufferedInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { public static String getBinaryHash(File apk, String algo) { FileInputStream fis = null; BufferedInputStream bis = null; try { MessageDigest md = MessageDigest.getInstance(algo); fis = new FileInputStream(apk); bis = new BufferedInputStream(fis); byte[] dataBytes = new byte[524288]; int nread = 0; while ((nread = bis.read(dataBytes)) != -1) md.update(dataBytes, 0, nread); byte[] mdbytes = md.digest(); return toHexString(mdbytes); } catch (IOException e) { Log.e("FDroid", "Error reading \"" + apk.getAbsolutePath() + "\" to compute " + algo + " hash."); return null; } catch (NoSuchAlgorithmException e) { Log.e("FDroid", "Device does not support " + algo + " MessageDisgest algorithm"); return null; } finally { closeQuietly(fis); } } /** * Computes the base 16 representation of the byte array argument. * * @param bytes an array of bytes. * @return the bytes represented as a string of hexadecimal digits. */ public static String toHexString(byte[] bytes) { BigInteger bi = new BigInteger(1, bytes); return String.format("%0" + (bytes.length << 1) + "X", bi); } public static void closeQuietly(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException ioe) { // ignore } } }