package com.tcl.ah.security;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1 {
    public static final String mAlgorithm ="SHA-1";

    public static String getHash(InputStream is)throws IOException,NoSuchAlgorithmException {
        MessageDigest mDigest =null ;
        byte mBuffer[]=new byte[1024*8];
        int len ;
        mDigest = MessageDigest.getInstance(mAlgorithm);
        while((len= is.read(mBuffer))!=-1){
            mDigest.update(mBuffer,0,len);
        }
        BigInteger bigInt = new BigInteger(1,mDigest.digest());
        return bigInt.toString(16);
    }
    public static String getHash(File file)throws IOException,NoSuchAlgorithmException{
        InputStream is =null;
        try {
            is = new FileInputStream(file);
            return getHash(is);
        }finally {
            try {
                if (is != null) is.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    public static String getHash(String value)throws IOException,NoSuchAlgorithmException{
        InputStream is =null;
        try{
            is = new ByteArrayInputStream(value.getBytes());
            return getHash(is);
        }finally {
            try {
                if (is != null) is.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
