简体   繁体   English

Base64 解码未完成

[英]Base64 Decode not complete

I have bee trying to decode some string returned from other system, but the decoded string have different result if i decode with online decoder or using PHP.我一直在尝试解码从其他系统返回的一些字符串,但是如果我使用在线解码器或使用 PHP 解码,解码后的字符串会产生不同的结果。 I've been trying using base64.StdEncoding.DecodeString() and base64.StdEncoding.Decode() but the result still not the same as the result of online decoder or PHP code.我一直在尝试使用base64.StdEncoding.DecodeString()base64.StdEncoding.Decode()但结果仍然与在线解码器或 PHP 代码的结果不同。

Here is my code:这是我的代码:

// encoded string
s := "HxJVICMcHCYeHUJcEWISWk09JgxHBwRPXHlHWFoGf1JXCkgFS1xXVU9Ze1FSCUwUIFMdGx0-SglVDmRNUHdAJRETRR0hHx0aIB1OExcgUCkeRyEaDUE5Y1oTREhcCRJSXAtWHBwfJSUYFUALUFd-VlkIU0JYFg5TA04PURA_OFBQXHpXWVxTSEZlC1FZTH4TKTUXGx1ORBcfSB0fO0xRJRoRVxsmExcoIhxEAxsQfF9bD1tXSQd-XEkBShEoPH80UWEJWAhAQhA0XgNVTwdWZxEX"

// add '=' on the right string
strHelper := string2.NewStringHelper()
sl := math.Ceil(float64(len(s) / 4 * 4))
sp := strHelper.StrPadRight(s, "=", int(sl))
sp = strtr(sp, map[string]string{"-_": "+/"})
  
// decode the string using base64.StdEncoding.DecodeString()
spb, _ := base64.StdEncoding.DecodeString(sp)
  
// decode the string using base64.StdEncoding.Decode()
b64 := make([]byte, base64.StdEncoding.DecodedLen(len(sp)))
n, err := base64.StdEncoding.Decode(b64, []byte(sp))

// decode the string using base64.NewDecoder()
b64s := strings.NewReader(sp)
b64d := base64.NewDecoder(base64.StdEncoding, b64s)
buf := new(strings.Builder)
io.Copy(buf, b64d)

// result of decoded string
U #&B\bZM=&GO\yGXZRW
HK\WUOY{QR L S

// result from online decoder or PHP
U #&B\bZM=&GO\yGXZRW
HK\WUOY{QR L S>J   UdMPw@%E! N P)G!
A9cZDH\    R\V%%@PW~VYSBXSNQ?8PP\zWY\SHFeQYL~)5NDH;LQ%W&("D|_[[WI~\IJ(<4Qa    X@B4^UOVg

https://go.dev/play/p/Yqf2I2QgWxS https://go.dev/play/p/Yqf2I2QgWxS

Please can someone enlightened me where my code is wrong?请问有人能告诉我我的代码哪里错了吗?

Never omit errors in Go!永远不要忽略 Go 中的错误! If you check it:如果你检查它:

data, err := base64.StdEncoding.DecodeString(s)
if err != nil {
    panic(err)
}

Output:输出:

panic: illegal base64 data at input byte 71

Your input is constructed not from the standard Base64 charset.您的输入不是从标准 Base64 字符集构造的。 The standard charset uses the + and / characters.标准字符集使用+/字符。 Your input is constructed using a modified charset, a charset safe and used to transmit encoded values in URLs which uses - and _ .您的输入是使用修改后的字符集构建的,这是一个安全的字符集,用于在使用-_的 URL 中传输编码值。

So decode using base64.URLEncoding :所以使用base64.URLEncoding解码:

data, err := base64.URLEncoding.DecodeString(s)
if err != nil {
    panic(err)
}

fmt.Println(string(data))

This will not result in an error (try it on the Go Playground ).这不会导致错误(在Go Playground上尝试)。

If your input does not contain the padding characters, then use base64.RawURLEncoding .如果您的输入不包含填充字符,则使用base64.RawURLEncoding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM