13

I have a problem with SHA-1 performance on Android. In C# I get calculated hash in about 3s, same calculation for Android takes about 75s. I think the problem is in reading operation from file, but I'm not sure how to improve performance.

Here's my hash generation method.

private static String getSHA1FromFileContent(String filename)
    {

        try
        {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            //byte[] buffer = new byte[65536]; //created at start.
            InputStream fis = new FileInputStream(filename);
            int n = 0;
            while (n != -1)
            {
                n = fis.read(buffer);
                if (n > 0)
                {
                    digest.update(buffer, 0, n);
                }
            }
            byte[] digestResult = digest.digest();
            return asHex(digestResult);
        }
        catch (Exception e)
        {
            return null;
        }
    }

Any ideas how can I improve performance?

keithbhunter
  • 12,258
  • 4
  • 33
  • 58
Tomasz Wójcik
  • 955
  • 10
  • 23

2 Answers2

4

I tested it on my SGS (i9000) and it took 0.806s to generate the hash for a 10.1MB file.

Only difference is that in my code i am using BufferedInputStream in addition to the FileInputStream and the hex conversion library found at:

http://apachejava.blogspot.com/2011/02/hexconversions-convert-string-byte-byte.html

Also I would suggest that you close your file input stream in a finally clause

DevProd
  • 573
  • 5
  • 6
  • 2
    This link is broken as of 11/10/15. – keithbhunter Nov 10 '15 at 13:43
  • Link is broken in 2017. – jpros Oct 09 '17 at 18:33
  • 1
    Dam this should be down voted just for posting an external url instead of writing answer here. – lukassos Apr 15 '18 at 18:49
  • Link is broken in 2021 – Francis Saa-Dittoh Jan 28 '21 at 10:20
  • The original source code of the plagiarised `HexConversions.java` file can be found on the original author's website (which unfortunately appears to now require authentication to access). An archived version (latest from 2017) can be found here: https://web.archive.org/web/20171115213622/http://www.idevelopment.info/data/Programming/java/io/HexConversions.java – Edric Aug 20 '21 at 15:44
1

If I were you I would use the JNI like this guy did and get the speed up that way. This is exactly what the C interface was made for.

Robert Massaioli
  • 13,379
  • 7
  • 57
  • 73