doubipiao1611
2019-06-12 09:44
浏览 97

Ruby vs.Go / sha256 hmac base64编码的字符串不匹配

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douju9847 2019-06-12 09:59
    已采纳

    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)
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题