Skip to content

Instantly share code, notes, and snippets.

@hamakn
Created July 21, 2016 07:23
Show Gist options
  • Save hamakn/1cd2e2e18518ff56fb2f72d10c95bfb8 to your computer and use it in GitHub Desktop.
Save hamakn/1cd2e2e18518ff56fb2f72d10c95bfb8 to your computer and use it in GitHub Desktop.
require "pry"
require "time"
require "digest"
require "net/http"
require "http_signatures"
## sample for http_signatures https://github.com/99designs/http-signatures-ruby
# GET
context = HttpSignatures::Context.new(
keys: {"examplekey" => "secret-key-here"},
algorithm: "hmac-sha256",
headers: ["(request-target)", "Date"],
)
message = Net::HTTP::Get.new(
"/path?query=123",
"Date" => Time.now.rfc822,
)
context.signer.sign message
p message["Signature"] # => "keyId=\"examplekey\",algorithm=\"hmac-sha256\",headers=\"(request-target) date\",signature=\"AM2PhT6PIyxETGakvGOi7NLZcaeLCnCKz+R16dKT2Sc=\""
p context.verifier.valid? message # => true
message["Signature"] = message["Signature"].gsub(/.=\"$/, "aa=\"")
p context.verifier.valid? message # => false
# POST
context = HttpSignatures::Context.new(
keys: {"examplekey" => "secret-key-here"},
algorithm: "hmac-sha256",
headers: ["(request-target)", "Date", "Digest"],
)
message = Net::HTTP::Post.new(
"/path",
"Date" => Time.parse("2016-07-21 15:30:00").rfc822,
)
message.set_form_data({ a: 1, b: 2 })
# see
# https://www.ietf.org/archive/id/draft-cavage-http-signatures-05.txt
# 3.1. Authorization Header
message["Digest"] = "SHA-256=#{Digest::SHA256.hexdigest(message.body)}"
context.signer.sign message
p context.verifier.valid? message # => true
message["Digest"] = message["Digest"] + "aa"
p context.verifier.valid? message # => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment