I have php web services for getting huge amount of data in JSON format. Currently i am using count of sending data and received data comparing for success case. Recently i heard method called checksum. How can i implement checksum in this scenario ?
You can sign the payload with hash_hmac(), with a known key, the token created would be passed through using HTTP headers.
For example:
<?php
// key which will sign the data
$key = hash('sha256', 'Unique user data or Some secret');
// your data
$array = [
'foobar' => 'baz'
];
// encode the payload
$json = json_encode($array);
// sign it with key
$token = hash_hmac('sha256', $json, $key);
// set response header
header('X-Checksum: '.$token);
echo $json;
This is how the receiver would verify the received data.
// faked: this would be populated by the request/response
$_POST['json'] = $json;
$_SERVER['X-Checksum'] = $token;
// verify the data matches token by signing the data with the key
$check = hash_hmac('sha256', $_POST['json'], $key);
if (hash_equals($token, $check)) {
echo 'Verified';
} else {
echo 'Tampered';
}
// example tampered data
$_POST['json'] = 'tampered'.$json;
$check = hash_hmac('sha256', $_POST['json'], $key);
if (hash_equals($token, $check)) {
echo 'Verified';
} else {
echo 'Tampered';
}
See it online: https://3v4l.org/tvUUR