Skip to content

Instantly share code, notes, and snippets.

@bentonporter
Created June 7, 2012 20:51
Show Gist options
  • Select an option

  • Save bentonporter/2891463 to your computer and use it in GitHub Desktop.

Select an option

Save bentonporter/2891463 to your computer and use it in GitHub Desktop.
Ruby - HMAC-SHA256 example
require 'openssl'
require 'Base64'
key = "secret-key"
data = "some data to be signed"
Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha256'), key, data)).strip()
@yazinsai

Copy link
Copy Markdown

OpenSSL::Digest::Digest is now deprecated. Use OpenSSL::Digest instead

@alovak

alovak commented Feb 28, 2015

Copy link
Copy Markdown

I was looking for how to create HMAC sha256 :D

@gr8bit

gr8bit commented Apr 1, 2015

Copy link
Copy Markdown

If you came here (like me) looking for a quick hint on how to encode hmac sha256 for Facebook's appsecret_proof parameter, this is what you are looking for:

OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), <app_secret>, <user_access_token>)

:)

@Bartuz

Bartuz commented Dec 16, 2015

Copy link
Copy Markdown

Nice guide by shopify how to verify webhooks
https://docs.shopify.com/api/webhooks/using-webhooks#verify-webhook

@jbonhag

jbonhag commented Feb 25, 2016

Copy link
Copy Markdown

What @gr8bit said.

@A1iAshoor

Copy link
Copy Markdown

secure_hash = OpenSSL::HMAC.hexdigest('SHA256', <key>, <data>)

@jamesfzhang

Copy link
Copy Markdown

Note that it's also very important to define what data to sign. In the Shopify example, they sign the POST request body (which makes sense for webhooks). So make sure you figure out what data you want to sign (request path, params, user auth data, nonce, etc), such that an attacker can at most replay the call, and cannot make other calls with the request signature.

@alexbrahastoll

Copy link
Copy Markdown

+1 for @gr8bit suggestion

@RicardoZeballos

Copy link
Copy Markdown

@A1iAshoor's example is what Stripe is using in its libraries. In case anyone else also writing tests for your webhooks.

@pallavsharma

Copy link
Copy Markdown

If you came here (like me) looking for a quick hint on how to encode hmac sha256 for Facebook's appsecret_proof parameter, this is what you are looking for:

OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), <app_secret>, <user_access_token>)

:)

Thanks, it works like a charm.

@Erickw

Erickw commented Nov 26, 2020

Copy link
Copy Markdown

OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), <app_secret>, <user_access_token>)

Thanks, it worked well here too!

@activeliang

Copy link
Copy Markdown

secure_hash = OpenSSL::HMAC.hexdigest('SHA256', <key>, <data>)

thx~

@Mth0158

Mth0158 commented Feb 1, 2022

Copy link
Copy Markdown

OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), <app_secret>, <user_access_token>)

Worked perfectly for Facebook API, thank you @gr8bit

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