playing around with imaginary, I'm attempting to create a ruby client.
For security reasons, I'd need to sign the url
Here is the go provided sample :
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
)
func main() {
signKey := "ea79b7fd-287b-4ffe-b941-bf983181783f"
urlPath := "/resize"
url := "https%3A%2F%2Fxyz"
urlQuery := "nocrop=true&type=jpeg&url=" + url + "&width=500"
h := hmac.New(sha256.New, []byte(signKey))
h.Write([]byte(urlPath))
h.Write([]byte(urlQuery))
buf := h.Sum(nil)
fmt.Println(base64.RawURLEncoding.EncodeToString(buf)
}
Converted to ruby, this gives us :
require 'openssl'
require 'base64'
signKey = "ea79b7fd-287b-4ffe-b941-bf983181783f"
urlPath = "/resize"
url = "https%3A%2F%2Fxyz"
urlQuery = "nocrop=true&type=jpeg&url=" + url + "&width=500"
digest = OpenSSL::Digest.new('sha256')
hmac = OpenSSL::HMAC.digest(digest, signKey, "#{urlPath}#{urlQuery}")
pp Base64.strict_encode64(hmac)
We're almost there , but there a slight issue, don't know if it is due to openssl or base64, but for example when I get this with go :
wClkWcUvI9ILs7noAr_HtnKpRCeeWBXE1Ne2C99sAco
I get the following with the ruby version :
wClkWcUvI9ILs7noAr/HtnKpRCeeWBXE1Ne2C99sAco=
With ruby, whatever's done, it ends up with a =
While go uses underscore, ruby use backslashes (this last one statement might be the result of pure unawareness about specific ruby parts, but let's just detail the issue)
What should be done to get the same output with both versions ? Why do we get a close but not exact result between those languages ?
Thanks a lot for the reply
The Go code uses the URL safe variant of base64 encoding where your Ruby code uses the normal version. The URL safe version uses -
and _
instead of +
and /
so that it is safe for use in URLs. The Ruby version also includes padding (the =
at the end).
You can use the URL safe version in Ruby, and you can also specify no padding to get the same result as Go:
Base64.urlsafe_encode64(hmac, false)