doubipiao1611 2019-06-12 09:44
浏览 100
已采纳

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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法