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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀