Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Created October 9, 2012 11:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save samarpanda/3857998 to your computer and use it in GitHub Desktop.
Save samarpanda/3857998 to your computer and use it in GitHub Desktop.
Adding content verification using hmac in php
<?php
function get_private_key_for_public_key($public_key) {
// extract private key from database or cache store
return 'private_key_user_id_9999';
}
// Data submitted
$data = $_GET['data'];
$data = json_decode(stripslashes($data), TRUE);
// User hit the end point API with $data, $signature and $public_key
$message = $data['data'];
$received_signature = $data['sig'];
$private_key = get_private_key_for_public_key($data['pubKey']);
$computed_signature = base64_encode(hash_hmac('sha1', $message, $private_key, TRUE));
if($computed_signature == $received_signature) {
echo "Content Signature Verified";
}else {
echo "Invalid Content Verification Signature";
}
?>
<?php
const $SUBMIT_URL = "http://mysite.com/hmac-receiver.php?data=";
//User public & private keys
$private_key = "";
$public_key = "";
//Data to be submitted
$data = "";
//Generate content verification signature
$sig = base64_encode(hash_hmac('sha1', $data, $private_key, TRUE));
//Prepare json data to be submitted
$json_data = json_encode(array('data'=>$data, 'sig'=>$sig, 'pubKey'=>$public_key));
//Submit to api
submit_to_api($SUBMIT_URL.urlencode($json_data));
?>
@volomike
Copy link

This is a great example of one-way communication. However, one also needs to think about improving this for two-way. In other words, when I get a response back from the API, I need to prove that it didn't get disrupted by MTM attack by challenging it with a keyed hash signature too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment