Skip to content

Instantly share code, notes, and snippets.

@bentonporter
Created June 7, 2012 20:51
Show Gist options
  • Save bentonporter/2891463 to your computer and use it in GitHub Desktop.
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

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

@alovak
Copy link

alovak commented Feb 28, 2015

I was looking for how to create HMAC sha256 :D

@gr8bit
Copy link

gr8bit commented Apr 1, 2015

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
Copy link

Bartuz commented Dec 16, 2015

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

@jbonhag
Copy link

jbonhag commented Feb 25, 2016

What @gr8bit said.

@A1iAshoor
Copy link

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

@jamesfzhang
Copy link

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

+1 for @gr8bit suggestion

@RicardoZeballos
Copy link

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

@pallavsharma
Copy link

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
Copy link

Erickw commented Nov 26, 2020

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

Thanks, it worked well here too!

@activeliang
Copy link

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

thx~

@Mth0158
Copy link

Mth0158 commented Feb 1, 2022

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