5

I am generating the SHA1 key in both PHP and Android to verify the file. But I am getting different keys for both PHP and Android.

Android :

  try {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        byte[] buffer = new byte[65536]; 
        InputStream fis = new FileInputStream(downloadFile.getPath());
        int n = 0;
        while (n != -1) {
            n = fis.read(buffer);
            if (n > 0) {
                digest.update(buffer, 0, n);
            }
        }
        fis.close();
        byte[] digestResult = digest.digest();
       log("CheckSum : " + byteArray2Hex(digestResult));
    } catch (Exception e) {
        log("Exception : " + e.getLocalizedMessage());
    }

PHP:

echo ' \nSHA1 File hash of '. $filePath . ': ' . sha1_file($filePath);

Checksum Output:

PHP SHA1 CheckSum : e7a91cd4127149a230f3dcb5ae81605615d3e1be Android SHA1 CheckSum : 19bcbd9d18a3880d2375bddb9181d75da3f32da0

Can anyone help how to handle this.

Kamalanathan
  • 1,747
  • 3
  • 22
  • 33
  • Can you give us the output for password for both? I'm pretty sure Java/Android outputs the raw hash. – Matt Feb 10 '16 at 05:20
  • I have updated the checksum output for the both android and php – Kamalanathan Feb 10 '16 at 05:23
  • Are we absolutely truly sure the input data is the same? – lc. Feb 10 '16 at 05:26
  • Yes I just copy and paste the same file in mobile for checking – Kamalanathan Feb 10 '16 at 05:28
  • @Kamal I've tested your code on my local environment, compiled and run with java 1.7 and php 7, I got the same sha1 output, please see: http://screencast.com/t/YtFGfn1m1j . can you add the code for the `byteArray2Hex` method? – kevinkl3 Feb 10 '16 at 05:39
  • @Kevin: can you check the byte to hex code Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); – Kamalanathan Feb 10 '16 at 05:44
  • @Kamal that works fine on my side, same output, the only chance here is that the file somehow is being modified. – kevinkl3 Feb 10 '16 at 05:49
  • @Kevin: Thanks, I got the issue. The byte to hex conversion code is wrong. I have modified that code now its working fine. – Kamalanathan Feb 10 '16 at 05:59

1 Answers1

1

From this SO answer: https://stackoverflow.com/a/9855338/3393666 consider using this byteArray2Hex function:

final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String byteArray2Hex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

I've tested it on java 1.7 vs PHP 7 and Android 5.0 compiled with SDK 23. Hope this helps.

Community
  • 1
  • 1
kevinkl3
  • 961
  • 7
  • 22