get File MD5 Hash - Android java.security

Android examples for java.security:Hash

Description

get File MD5 Hash

Demo Code


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class Main{
    public static void getFileMD5(String file, IHashState cb) {
        getFileHash("MD5", file, cb);
    }/*w  w w.j  av  a  2 s  .c  o  m*/
    private static void getFileHash(final String algo, final String file,
            final IHashState cb) {
        if (cb == null) {
            return;
        }

        final File f = new File(file);
        if (!f.exists() || !f.canRead()) {
            cb.onFinish(file, null);
            return;
        }

        HDBThreadUtils.runOnWorker(new Runnable() {
            @Override
            public void run() {
                MessageDigest md;
                try {
                    md = MessageDigest.getInstance(algo);
                    md.reset();

                    InputStream is = new FileInputStream(f);
                    byte[] buffer = new byte[4 * 1024]; // optimal size is 4K
                    long available = is.available();
                    long processed = 0;

                    int read = 0;
                    do {
                        read = is.read(buffer);
                        if (read > 0) {
                            md.update(buffer, 0, read);
                            processed += read;
                            cb.onProgress(file, processed, available);
                        }
                    } while (read > 0);

                    is.close();

                    byte[] b = md.digest();
                    cb.onFinish(file, binaryToHexString(b));
                } catch (Exception e) {
                    cb.onFinish(file, null);
                }
            }
        });
    }
    public static String binaryToHexString(byte[] messageDigest) {
        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++) {
            int by = 0xFF & messageDigest[i];
            if (by < 0x10) {
                hexString.append("0").append(Integer.toHexString(by));
            } else if (by >= 0x10) {
                hexString.append(Integer.toHexString(by));
            }
        }
        return hexString.toString();
    }
}

Related Tutorials