Android SHA1 Hash Create sha1(File input)

Here you can find the source of sha1(File input)

Description

sha

Declaration

public static final String sha1(File input) throws IOException 

Method Source Code

//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static final String sha1(String input) {
        return hash(input, "SHA-1");
    }//from w w w .j a va2  s .  co m

    public static final String sha1(File input) throws IOException {
        return hash(input, "SHA-1");
    }

    public static final String hash(String input, String algorithm) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] messageDigest = md.digest(input.getBytes());
            return toHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static final String hash(File file, String algorithm)
            throws IOException {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            InputStream is = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int read = 0;
            while ((read = is.read(buffer)) > 0) {
                md.update(buffer, 0, read);
            }
            is.close();
            byte[] messageDigest = md.digest();
            return toHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
    }

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            int unsignedB = b & 0xff;
            if (unsignedB < 0x10)
                sb.append("0");
            sb.append(Integer.toHexString(unsignedB));
        }
        return sb.toString();
    }
}

Related

  1. dataDigest(String in)
  2. SHA1(String s)
  3. SHA1(String text)
  4. SHA256(String text)
  5. HashPassword(String text)
  6. sha1(String input)
  7. sha1(String ori)
  8. sha1(String ori)
  9. sha1(String s)