Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, calculating SHA-1 hash from file, fastest algorithm

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?

like image 520
Tomasz Wójcik Avatar asked Apr 06 '11 10:04

Tomasz Wójcik


1 Answers

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

like image 163
DevProd Avatar answered Sep 18 '22 16:09

DevProd