英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论