Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA1 Checksum is getting different for same file in both php and android

Tags:

android

php

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.

like image 766
Kamalanathan Avatar asked Nov 09 '22 20:11

Kamalanathan


1 Answers

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.

like image 147
kevinkl3 Avatar answered Nov 14 '22 23:11

kevinkl3