[英]golang base64 encoding vs nodejs buffer base64 encoding
I'm using a piece of software that base64 encodes in node as follows: 我正在使用base64在node中编码的软件,如下所示:
const enc = new Buffer('test', 'base64')
console.log(enc)
displays: console.log(enc)
显示:
<Buffer b5 eb 2d>
I'm writing a golang service that needs to interoperate with this. 我正在写一个需要与此互操作的golang服务。 But I can't reproduce the above result in go.
但是我无法在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.
我怀疑不同之处在于节点将字符串存储为base64字符串中的字节,而go将字符串存储为ascii / utf8字符串中表示为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. 我略过go源进行编码,然后尝试找到Buffer的Node源,但是经过一会儿的搜索后,决定在此处发布可能会更快,希望有人能立即获得答案。
This constructor: 此构造函数:
new Buffer('test', 'base64')
Decodes the input string test
, using base64
encoding. 使用
base64
编码对输入字符串test
进行解码。 It does not encode the test
using base64. 它不使用base64编码
test
。 See the reference : 请参阅参考资料 :
new Buffer(string[, encoding])
string
String to encode.string
要编码的string
。encoding
The encoding ofstring
.encoding
string
的编码。 Default:'utf8'
.默认值:
'utf8'
。
The equivalent Go code would be: 等效的Go代码为:
data, err := base64.StdEncoding.DecodeString("test")
if err != nil {
panic(err)
}
fmt.Printf("% x", data)
Which outputs (try it on the Go Playground ): 哪些输出(在Go Playground上尝试):
b5 eb 2d
To encode in Node.js, use (for details see How to do Base64 encoding in node.js? ): 要在Node.js中进行编码,请使用(有关详细信息,请参见如何在node.js中进行Base64编码? ):
Buffer.from("test").toString('base64')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.