我正在嘗試將Node.js腳本轉(zhuǎn)換為Golang。"error: illegal base64 data at input byte 40"但是,我在解碼Base64時總是出錯??赡苡腥藥椭遥呀?jīng)調(diào)試和閱讀了幾個小時的文檔......需要幫助!// 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 hereconst 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_-
1 回答

一只萌萌小番薯
TA貢獻(xiàn)1795條經(jīng)驗 獲得超7個贊
首先,去掉strings.Replaces 而只使用base64.URLEncoding而不是StdEncoding,因為 URL 字母表顯然是您的數(shù)據(jù)所在。
此外,標(biāo)準(zhǔn) base64 數(shù)據(jù)已填充,但您的數(shù)據(jù)未填充,因此您需要“原始”編碼,即base64.RawURLEncoding. 這有效:
firstPart := parts[0]
signatureByte, err := base64.RawURLEncoding.DecodeString(firstPart)
https://play.golang.org/p/Pj_LLfirU8M
有關(guān)更多信息,請參閱base64包文檔和base64 標(biāo)準(zhǔn)。
- 1 回答
- 0 關(guān)注
- 212 瀏覽
添加回答
舉報
0/150
提交
取消