Data Tampering - Hash with Cookie or Form

Data Tampering

Sending the hash:

Checking the hash:

Hash with Cookie

Sending the cookie

<?php
$secret_word = 'salt-baked squid';
$id = 31415926;
$hash = md5($secret_word.$id);
setcookie('id',$id.'-'.$hash);
?>

Receiving and verifying the cookie

<?php
list($c_id,$c_hash) = explode('-',$_COOKIE['id']);
if (md5($secret_word.$c_id) == $c_hash) {
    $id = $c_id;
} else {
    die('Invalid cookie.');
}
?>

Hash with Form

Displaying the Form

<?php
$secret_word = 'salt-baked squid';
$id = 31415926;
$hash = md5($secret_word.$id);
print<<<_HTML_
<form method="POST" action="save.php">
<input type="hidden" name="id" value="$id">
<input type="hidden" name="hash" value="$hash">
... other form elements ...
</form>
_HTML_;
?>

Processing the Form

<?php
if (md5($secret_word.$_POST['id']) == $_POST['hash']) {
    $id = $_POST['id'];
} else {
    die('Invalid ID');
}
?>

Hashing Multiple Values

<?php
$secret_word = 'salt-baked squid';
$var_names = array('id','shopping_cart','size');
$vars_string = serialize(compact($var_names));
$hash = md5($secret_word.$vars_string);
$vars_safe = htmlspecialchars($vars_string);
print<<<_HTML_
<form method="POST" action="save.php">
<input type="hidden" name="vars" value="$vars_safe">
  <input type="hidden" name="hash" value="$hash">
... other form elements ...
</form>
_HTML_;
?>

Processing the Form

<?php
if (md5($secret_work.$_POST['vars']) == $_POST['hash']) {
    $vars = unserialize($_POST['vars']);
    // put back into global namespace
    extract($vars);
} else {
    die('Invalid vars');
}
?>