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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛