go - Golang Base64签名验证VS CryptoJS

标签 go

我正在尝试将Node.js脚本 转换为Golang。但是,我在解码Base64时总是收到"error: illegal base64 data at input byte 40"错误。有人可以帮我,已经调试和阅读文档几个小时了……需要帮助!

// Node.js exampe (code copied from Facebook Instant game SDK example)
const CryptoJS = require('crypto-js');
var firstpart = signedRequest.split('.')[0];
firstpart = firstpart.replace(/-/g, '+').replace(/_/g, '/');
const signature = CryptoJS.enc.Base64.parse(firstpart).toString(); // <-- fail here
const dataHash = CryptoJS.HmacSHA256(signedRequest.split('.')[1], '<APP_SECRET>').toString();
var isValid = signature === dataHash;
const json = CryptoJS.enc.Base64.parse(signedRequest.split('.')[1]).toString(CryptoJS.enc.Utf8);
const data = JSON.parse(json);

上面的代码是Facebook的示例代码,下面的代码(如下)是我写的。

    parts := strings.Split(signedRequest, ".")
    firstPart := parts[0]
    replaced := strings.Replace(firstPart, "-", "+", -1)
    replaced = strings.Replace(replaced, "_", "/", -1)

    signatureByte, err := base64.StdEncoding.DecodeString(replaced) // <-- ERROR here
    if err != nil {
        fmt.Println("error:", err)
        return false, err
    }
    signature := string(signatureByte)

    dataHash := createHmacSHA256(parts[1], "<APP_SECRET>") // TODO: not sure, to string or hex string?

    isValid := signature == dataHash
    if isValid {
        return true, nil
    }


Go Playground在这里https://play.golang.org/p/ilSbqamFdV_-

最佳答案

首先,摆脱strings.Replace,而只使用base64.URLEncoding而不是StdEncoding,因为URL字母显然是您的数据所在的位置。

另外,标准的base64数据会被填充,但数据不会被填充,因此您需要“原始”编码,即base64.RawURLEncoding。这有效:

firstPart := parts[0]
signatureByte, err := base64.RawURLEncoding.DecodeString(firstPart)

https://play.golang.org/p/Pj_LLfirU8M

有关更多信息,请参见 base64 package docsbase64 standard

关于go - Golang Base64签名验证VS CryptoJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60938014/

相关文章:

具有可选计数的 Golang 数据存储查询

go - 以时间表示的字符串时间。时间

go - 不正确的数据重传

templates - 内置 "html/template"或 "mustache",我应该使用哪个?

arrays - 结构问题中的 Golang 数组

Golang 中的结构文字

Go 类型推断和命名返回变量

escaping - 编码/解码 URL 的推荐方法

go - 在 Golang 中使用字节数组附加/创建 SVG

go - 将 json 解码为类型