Skip to content

Instantly share code, notes, and snippets.

@fmp777
Forked from twslankard/gist:637020
Last active April 25, 2019 02:20
Show Gist options
  • Save fmp777/0c74c03f950c9704be5cd568ddfe48ad to your computer and use it in GitHub Desktop.
Save fmp777/0c74c03f950c9704be5cd568ddfe48ad to your computer and use it in GitHub Desktop.
Verifying Amazon SNS Notification Signatures
<?php
function verifyPost()
{
// get the raw HTTP post data
$postdata = file_get_contents('php://input');
// the post data is JSON, so let's decode it and grab the various fields
$json = json_decode($postdata);
$subject = $json->Subject;
$message = $json->Message;
$signature = $json->Signature;
$message_id = $json->MessageId;
$timestamp = $json->Timestamp;
$topic_arn = $json->TopicArn;
$type = $json->Type;
// decode the signature
$decoded_signature = base64_decode($signature);
// generate the canonical string that will be used to verify the signature
$data = "Message\n$message\nMessageId\n$message_id\n";
// only add the subject if it is set
if($subject != null) {
$data .= "Subject\n$subject\n";
}
$data .= "Timestamp\n$timestamp\nTopicArn\n$topic_arn\nType\n$type\n";
$data = utf8_encode($data);
// grab the Amazon SNS certificate file
$cert = file_get_contents($json->SigningCertURL);
// retrieve the public key from the certificate
$pkeyid = openssl_get_publickey($cert) or die("Couldn't read public key");
// verifiy the canonical string using the public key and the decoded signature
$ok = openssl_verify($data, $decoded_signature, $pkeyid, OPENSSL_ALGO_SHA1);
// free the key from memory
openssl_free_key($pkeyid);
if ($ok == 1) {
// signature was good
return $json;
} elseif ($ok == 0) {
// signature was bad
return false;
} else {
// and error occurred
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment