Issues with SHA1 hash implementation in Android

前端 未结 4 691
自闭症患者
自闭症患者 2020-12-13 11:33

I have two small snippets for calculating SHA1.

One is very fast but it seems that it isn\'t correct and the other is very slow but correct.
I think the F

4条回答
  •  醉酒成梦
    2020-12-13 12:06

        public void computeSHAHash(String path)// path to your file
        {
                String SHAHash = null;
        try 
        {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            InputStream in = new FileInputStream(path);
            byte[] buf = new byte[8192];
            int len = -1;
            while((len = in.read(buf)) > 0) 
            {
                md.update(buf, 0, len);
            }
            in.close();
            byte[] data = md.digest();
            try 
            {
               SHAHash = convertToHex(data);
            } 
            catch (IOException e) 
            {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          Toast.makeToast(getApplicationContext(),"Generated Hash ="+SHAHash,Toast.LENGTH_SHORT).show();  
    
       }
     private static String convertToHex(byte[] data) throws java.io.IOException
    {
        StringBuffer sb = new StringBuffer();
        String hex = null;
    
        hex = Base64.encodeToString(data, 0, data.length, NO_OPTIONS);
    
        sb.append(hex);
    
        return sb.toString();
    }
    

提交回复
热议问题