Skip to main content

Moving HMAC generation in Ruby out of the way to post to the Known API

2 min read

As I'm currently trying to post something through the Known API to my
site I have to dive into [HMAC](https://en.wikipedia.org/wiki/HMAC) a bit.

It's actually not that complicated and Phyks has laid out all the necessary steps to use the API in his excellent [article](https://known.phyks.me/2015/publishing-through-the-known-api).

However, buildung the HMAC somehow it didn't seem to work when I used something like

```ruby
statusurl = '/status/edit'
hash = OpenSSL::HMAC.digest('sha256', apikey, statusurl)
hmac = Base64.encode64(hash)
```

to generate the value. It showed up correct on screen, but my HTTPS request turned resulted in an HTTP 400 reply.

Lo and behold, after some debugging with ```http.set_debug_output($stdout)``` I found the culprit. ```encode64``` adds a newline at the end (as by the spec) which, put into the HTTP header, breaks your request.

Thanks to the pointers in [StackOverflow post](http://stackoverflow.com/questions/2620975/strange-n-in-base64-encoded-string-in-ruby) there's ```strict_encode64``` to the rescue. So

```ruby
statusurl = '/status/edit'
hash = OpenSSL::HMAC.digest('sha256', apikey, statusurl)
hmac = Base64.strict_encode64(hash)
```

will give you an HMAC that makes your HTTP request happy. Or you can strip the newline using ```gsub```, your call. Yay, now my requests are working. On to the next step!

Tags: