golang输入字节处的base64数据非法

huangapple go评论90阅读模式
英文:

golang illegal base64 data at input byte

问题

Python

import base64

print(base64.b64decode('//Py+vX7suTx8A=='))

Go

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	data, err := base64.RawStdEncoding.DecodeString("//Py+vX7suTx8A==")
	fmt.Println(err)
}

为什么 Python 可以解码这个字符串,而 Go 却失败了?

英文:

Python

>>> print(base64.b64decode('//Py+vX7suTx8A=='))
b'\xff\xf3\xf2\xfa\xf5\xfb\xb2\xe4\xf1\xf0'

Go

>>> data, err := base64.RawStdEncoding.DecodeString("//Py+vX7suTx8A==")
err -> illegal base64 data at input byte 14

Why can Python decode this string while Go fails?

答案1

得分: 2

RawStdEncoding,顾名思义,接受“原始”的base64编码字符串。而你使用的字符串则使用了2个“=”进行填充。尝试移除它们,你应该就不会出现错误了:

data, err := base64.RawStdEncoding.DecodeString("//Py+vX7suTx8A") // 没有填充
if err != nil {
    fmt.Printf("err: %v\n", err)
}

fmt.Printf("data: %v\n", data)

正如@JimB所说,如果你仍然想解码填充的字符串,只需使用带填充版本的base64.StdEncoding

data, err := base64.StdEncoding.DecodeString("//Py+vX7suTx8A==")
if err != nil {
    fmt.Printf("err: %v\n", err)
}

fmt.Printf("data: %v\n", data)
英文:

RawStdEncoding, as its name suggests, accepts "raw" base64 encoded strings. The string you used on the other hand is padded with 2 "="s. try removing them and you should get no errors:

data, err := base64.RawStdEncoding.DecodeString("//Py+vX7suTx8A") // no paddings
	if err != nil {
		fmt.Printf("err: %v\n", err)
	}

	fmt.Printf("data: %v\n", data)

And as @JimB said, if you want to decode padded strings anyway, just use base64.StdEncoding with the padded version.

data, err := base64.StdEncoding.DecodeString("//Py+vX7suTx8A==")
	if err != nil {
		fmt.Printf("err: %v\n", err)
	}

	fmt.Printf("data: %v\n", data)

huangapple
  • 本文由 发表于 2023年4月2日 20:31:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75912030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定