get File Digest Encrypt - Android java.security

Android examples for java.security:Decrypt Encrypt

Description

get File Digest Encrypt

Demo Code


//package com.java2s;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {

    public static String getFileDigestEncrypt(File file, String algorithm)
            throws IOException {
        MessageDigest digest = null;
        try {//  w ww  . j  av  a  2  s .  c  om
            digest = MessageDigest.getInstance(algorithm);
            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[1024 * 1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                digest.update(buffer, 0, len);
            }
            in.close();
            return bytes2String(digest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String bytes2String(byte digest[]) {
        String str = "";
        String tempStr = "";
        for (int i = 0; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            } else {
                str += tempStr;
            }
        }
        return str;
    }
}

Related Tutorials