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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据