drpqxogph15436713 2018-08-01 06:20
浏览 72
已采纳

golang base64编码vs nodejs缓冲区base64编码

I'm using a piece of software that base64 encodes in node as follows:

const enc = new Buffer('test', 'base64')

console.log(enc) displays:

<Buffer b5 eb 2d>

I'm writing a golang service that needs to interoperate with this. But I can't reproduce the above result in go.

package main

import (
    "fmt"
    b64 "encoding/base64"
)

func main() {
    // Attempt 1
    res := []byte(b64.URLEncoding.EncodeToString([]byte("test")))
    fmt.Println(res)
    // Attempt 2
    buf := make([]byte, 8)
    b64.URLEncoding.Encode(buf, []byte("test"))
    fmt.Println(buf)
}

The above prints:

[100 71 86 122 100 65 61 61]
[100 71 86 122 100 65 61 61]

both of which are rather different from node's output. I suspect the difference is that node is storing the string as bytes from a base64 string, while go is storing the string as bytes from an ascii/utf8 string represented as base64. But haven't figured out how to get go to do as node is doing!

I skimmed the go source for the encoding, then attempted to find the Node source for Buffer, but after a little while hunting decided it would probably be much quicker to post here in the hope someone knew the answer off-hand.

  • 写回答

1条回答 默认 最新

  • dongmeng9048 2018-08-01 06:33
    关注

    This constructor:

    new Buffer('test', 'base64')
    

    Decodes the input string test, using base64 encoding. It does not encode the test using base64. See the reference:

    new Buffer(string[, encoding])
    
    • string String to encode.
    • encoding The encoding of string. Default: 'utf8'.

    The equivalent Go code would be:

    data, err := base64.StdEncoding.DecodeString("test")
    if err != nil {
        panic(err)
    }
    fmt.Printf("% x", data)
    

    Which outputs (try it on the Go Playground):

    b5 eb 2d
    

    To encode in Node.js, use (for details see How to do Base64 encoding in node.js?):

    Buffer.from("test").toString('base64')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 求制作一个个人网页,
    • ¥15 寻涂色内存脚本作者有项目有市场有资源.却技术
    • ¥15 蓝桥杯c51单片机问题
    • ¥15 ajax跨域问题请求修改代码
    • ¥15 python matplotlib
    • ¥15 短信测压+语音,有偿,必须用Python
    • ¥20 COCOS2DX的protobuf协议注册函数问题
    • ¥15 (标签-Pytorch|关键词-Stream)
    • ¥15 求深圳2019年开放数据应用创新大赛的营运车辆数据!
    • ¥15 软件UI界面绘制折线图