SHA1 checksum is different from the same file in both php and android

I generate the SHA1 key in PHP and Android to verify the file. But I have different keys for 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 deal with this.

+4
source share
1 answer

From this SO answer: fooobar.com/questions/15821 / ... 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 tested it on java 1.7 vs PHP 7 and Android 5.0 compiled with SDK 23. Hope this helps.

0

Source: https://habr.com/ru/post/1628065/


All Articles