Skip to content

Instantly share code, notes, and snippets.

@Mic92
Created January 18, 2018 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mic92/ff4bf09739c1f9cff2d82bf6eeae7161 to your computer and use it in GitHub Desktop.
Save Mic92/ff4bf09739c1f9cff2d82bf6eeae7161 to your computer and use it in GitHub Desktop.
use Digest::HMAC_SHA1;
# nix-shell -p perlPackages.DigestHMAC
# @body: full http post body
# @signature: value of X-Hub-Signature header field
# @secret_key: value configured in https://developer.github.com/v3/repos/hooks/#create-hook-config-params
# return: 1 if signature is correct
sub verify_signature {
my ($body, $signature, $secret_key) = (@_);
my $hmac_ctx = Digest::HMAC_SHA1->new($secret_key);
$hmac_ctx->add($body);
my $digest = $hmac_ctx->hexdigest;
# constant-time string comparison
if (length($signature) != length($digest)) {
return 0;
}
my $res = 0;
for (my $i=0; $i <= length($digest); $i++) {
$res |= (substr($digest, $i, 1) ^ substr($signature, $i, 1));
}
return $res == 0;
}
# $ ruby -ropenssl -e 'puts OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha1"), "3998803efb39cdb05b0742e1d1f85f15762ff6aa", "abc")'
# 7ccf3f9f79a260322c065bbf75e56bb90078e482
# print verify_signature("abc", "7ccf3f9f79a260322c065bbf75e56bb90078e482", "3998803efb39cdb05b0742e1d1f85f15762ff6aa");
## untested hydra fix
# my $header_signature = $c->request->headers->header('X-Hub-Signature') or die "no X-Hub-Signature set";
# verify_signature($c->request, $header_signature, "<ADD-GITHUB-SECRET>") or die "X-Hub-Signature invalid";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment