Android SHA1 Hash Create sha1(String input)

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

Description

sha

Declaration

public static final String sha1(String input) 

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");
    }// w  w w.j  a v a  2 s.c o  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. SHA1(String s)
  2. SHA1(String text)
  3. SHA256(String text)
  4. HashPassword(String text)
  5. sha1(File input)
  6. sha1(String ori)
  7. sha1(String ori)
  8. sha1(String s)
  9. sha1(String s)