Simon
Simon

Reputation: 2246

Verfying file data integrity between Android and PHP

My Android application downloads data as a file from my server.

I want to verify that the file content has not been tampered with during the transfer.

At this point, I thought of using a CRC32 value generated on the server and transferred to the Android client over a secure connection.

However, the value generated in PHP is not the same as the one generated on the Android client. Here is how I am calculating the CRC32 value in PHP :

$Crc32 = hash_file('crc32b', $output_file);

Here is my code generation for Android :

boolean bOk = true;
File fTarget = null;
FileInputStream fis;
CRC32 crc32;
byte[] btData;
int iCount;
int iCrc32;
String strCrc32;

btData = new byte[1024];
crc32 = new CRC32();

try
{
    fTarget = new File(DOWNLOAD_TARGET_PATH);
    fis = new FileInputStream(fTarget);

    while((iCount = fis.read(btData)) != -1)
    {
        crc32.update(btData, 0, iCount);
    }
    fis.close();
}
catch(Exception e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

iCrc32 = Integer.reverseBytes((int)crc32.getValue());
strCrc32 = String.format("%08x", iCrc32);
bOk = strCrc32.contentEquals(data.m_strCrc32);

if(!bOk && fTarget != null)
{
    // delete the file as it could be dangerous
    fTarget.delete();
}
return bOk;

I inverted the byte order as, during debugging, I saw that it did not match.

Everything works great in a debug build, but when I create the release build, it does not work.

What is the correct way to do this ?

Upvotes: 0

Views: 172

Answers (1)

Simon
Simon

Reputation: 2246

Here's the solution to the problem : Byte Order !

In my case, I develop with a Windows server and my production server is Linux. This means that, when CRC32 values are calculated, byte order is of importance.

Therefore, when the server is Windows, reversing the byte order is correct :

iCrc32 = Integer.reverseBytes((int)crc32.getValue());

But when the server is Linux (the same OS upon which Android is built), byte order should not be reversed.

iCrc32 = (int)crc32.getValue();

I hope that this will be of use to someone here.

Upvotes: 1

Related Questions