-
-
Save fmp777/0c74c03f950c9704be5cd568ddfe48ad to your computer and use it in GitHub Desktop.
Verifying Amazon SNS Notification Signatures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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